Skip to content

Commit

Permalink
refactor: AddWinsSet and HashGraph
Browse files Browse the repository at this point in the history
  • Loading branch information
h3lio5 committed Aug 18, 2024
1 parent 359e52e commit 61057f0
Show file tree
Hide file tree
Showing 5 changed files with 298 additions and 302 deletions.
2 changes: 1 addition & 1 deletion packages/crdt/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
"build": "tsc -b",
"clean": "rm -rf dist/ node_modules/",
"prepack": "tsc -b",
"test": "vitest --reporter=verbose"
"test": "vitest"
},
"dependencies": {},
"devDependencies": {
Expand Down
56 changes: 35 additions & 21 deletions packages/crdt/src/builtins/AddWinsSet/index.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,38 @@
/// GSet with support for state and op changes
export class AddWinsSet<T extends number> {
private _addSet: Set<T>;
private _removeSet: Set<T>;

constructor(addSet: Set<T>, removeSet: Set<T>) {
this._addSet = addSet;
this._removeSet = removeSet;
}

add(element: T): void {
this._addSet.add(element);
}

remove(element: T): void {
this._removeSet.add(element);
}
export class AddWinsSet<T> {
private state: Map<T, number>;

constructor() {
this.state = new Map();
}

add(value: T): void {
this.state.set(value, (this.state.get(value) || 0) + 1);
}

remove(value: T): void {
// We don't actually remove, just increment the counter
this.add(value);
}

getValue(value: T): number {
return this.state.get(value) || 0;
}

isInSet(value: T): boolean {
const count = this.getValue(value);
return count > 0 && count % 2 === 1;
}

values(): T[] {
return Array.from(this.state.entries())
.filter(([_, count]) => count % 2 === 1)
.map(([value, _]) => value);
}

read(): T {
const addResult = Array.from(this._addSet).reduce((acc, val) => acc + val, 0);
const removeResult = Array.from(this._addSet).reduce((acc, val) => acc + val, 0);
return (addResult - removeResult) as T;
merge(other: AddWinsSet<T>): void {
for (const [value, count] of other.state) {
this.state.set(value, Math.max(this.getValue(value), count));
}
}
}
}
Loading

0 comments on commit 61057f0

Please sign in to comment.