-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathin-memory-persistence.ts
More file actions
77 lines (67 loc) · 2.26 KB
/
in-memory-persistence.ts
File metadata and controls
77 lines (67 loc) · 2.26 KB
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import { IAccumulatorState, IUniversalAccumulatorState } from './IAccumulatorState';
import { IInitialElementsStore } from './IInitialElementsStore';
/**
* In memory implementation of the state. For testing only
*/
export class InMemoryState implements IAccumulatorState {
// Converts item to string (JSON.stringify) before adding to set as equality checks wont work with Uint8Array.
state: Set<string>;
constructor() {
this.state = new Set<string>();
}
async add(element: Uint8Array): Promise<void> {
const key = InMemoryState.key(element);
if (this.state.has(key)) {
throw new Error(`${element} already present`);
}
this.state.add(key);
return Promise.resolve();
}
async remove(element: Uint8Array): Promise<void> {
const key = InMemoryState.key(element);
if (!this.state.has(key)) {
throw new Error(`${element} not present`);
}
this.state.delete(key);
return Promise.resolve();
}
async has(element: Uint8Array): Promise<boolean> {
const key = InMemoryState.key(element);
return Promise.resolve(this.state.has(key));
}
static key(element: Uint8Array) {
return JSON.stringify(Array.from(element));
}
}
export class InMemoryUniversalState extends InMemoryState implements IUniversalAccumulatorState {
elements(): Promise<Iterable<Uint8Array>> {
function* y(state: Set<string>) {
for (const k of state) {
yield new Uint8Array(JSON.parse(k));
}
}
return Promise.resolve(y(this.state));
}
}
export class InMemoryInitialElementsStore implements IInitialElementsStore {
// Converts item to string (JSON.stringify) before adding to set as equality checks wont work with Uint8Array.
store: Set<string>;
constructor() {
this.store = new Set<string>();
}
async add(element: Uint8Array): Promise<void> {
const key = InMemoryInitialElementsStore.key(element);
if (this.store.has(key)) {
throw new Error(`${element} already present`);
}
this.store.add(key);
return Promise.resolve();
}
async has(element: Uint8Array): Promise<boolean> {
const key = InMemoryInitialElementsStore.key(element);
return Promise.resolve(this.store.has(key));
}
static key(element: Uint8Array) {
return JSON.stringify(Array.from(element));
}
}