This repository has been archived by the owner on Sep 30, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 16
/
LWW-Set.js
53 lines (51 loc) · 2.18 KB
/
LWW-Set.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import CRDTSet from './CmRDT-Set.js'
/**
* LWWSet-Set
*
* Operation-based Last-Write-Wins Set CRDT
*
* See base class CmRDT-Set.js for the rest of the API
* https://github.com/orbitdb/crdts/blob/master/src/CmRDT-Set.js
*
* Sources:
* "A comprehensive study of Convergent and Commutative Replicated Data Types"
* http://hal.upmc.fr/inria-00555588/document, "Figure 8: LWW-Set (state-based)"
*/
export default class LWWSet extends CRDTSet {
/**
* @override
*
* _resolveValueState function is used to determine if an element is present in a Set.
*
* It receives a Set of add tags and a Set of remove tags for an element as arguments.
* It returns true if an element should be included in the state and false if not.
*
* Overwriting this function gives us the ability to compare add/remove operations
* of a particular element (value) in the set and determine if the value should be
* included in the set or not. The function gets called once per element and returning
* true will include the value in the set and returning false will exclude it from the set.
*
* @param {[type]} added [Set of added elements]
* @param {[type]} removed [Set of removed elements]
* @param {[type]} compareFunc [Comparison function to compare elements with]
* @return {[type]} [true if element should be included in the current state]
*/
_resolveValueState (added, removed, compareFunc) {
// Sort both sets with the given comparison function
// or use "distance" sort by default
compareFunc = compareFunc ? compareFunc : (a, b) => (a || 0) - (b || 0)
const sortedAdded = Array.from(added).sort(compareFunc).reverse()
const sortedRemoved = Array.from(removed).sort(compareFunc).reverse()
// If the latest add operation is greater or equal than latest remove operation,
// we include it in the state
return compareFunc(sortedAdded[0], sortedRemoved[0]) > -1
}
/**
* Create LWWSet from a json object
* @param {[Object]} json [Input object to create the LWWSet from. Needs to be: '{ values: [] }']
* @return {[LWWSet]} [new LWWSet instance]
*/
static from (json) {
return new LWWSet(json.values)
}
}