1 |
|
2 | /* Based on the Hypothetical Amnesia Machine thought experiment */
|
3 | function HAM(machineState, incomingState, currentState, incomingValue, currentValue){
|
4 | if(machineState < incomingState){
|
5 | return {defer: true}; // the incoming value is outside the boundary of the machine's state, it must be reprocessed in another state.
|
6 | }
|
7 | if(incomingState < currentState){
|
8 | return {historical: true}; // the incoming value is within the boundary of the machine's state, but not within the range.
|
9 |
|
10 | }
|
11 | if(currentState < incomingState){
|
12 | return {converge: true, incoming: true}; // the incoming value is within both the boundary and the range of the machine's state.
|
13 |
|
14 | }
|
15 | if(incomingState === currentState){
|
16 | if(Lexical(incomingValue) === Lexical(currentValue)){ // Note: while these are practically the same, the deltas could be technically different
|
17 | return {state: true};
|
18 | }
|
19 | /*
|
20 | The following is a naive implementation, but will always work.
|
21 | Never change it unless you have specific needs that absolutely require it.
|
22 | If changed, your data will diverge unless you guarantee every peer's algorithm has also been changed to be the same.
|
23 | As a result, it is highly discouraged to modify despite the fact that it is naive,
|
24 | because convergence (data integrity) is generally more important.
|
25 | Any difference in this algorithm must be given a new and different name.
|
26 | */
|
27 | if(Lexical(incomingValue) < Lexical(currentValue)){ // Lexical only works on simple value types!
|
28 | return {converge: true, current: true};
|
29 | }
|
30 | if(Lexical(currentValue) < Lexical(incomingValue)){ // Lexical only works on simple value types!
|
31 | return {converge: true, incoming: true};
|
32 | }
|
33 | }
|
34 | return {err: "you have not properly handled recursion through your data or filtered it as JSON"};
|
35 | }
|
36 | if(typeof JSON === 'undefined'){
|
37 | throw new Error(
|
38 | 'JSON is not included in this browser. Please load it first: ' +
|
39 | 'ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js'
|
40 | );
|
41 | }
|
42 | var Lexical = JSON.stringify, undefined;
|
43 | module.exports = HAM;
|
44 | |
\ | No newline at end of file |