-
Notifications
You must be signed in to change notification settings - Fork 212
/
scratch.js
53 lines (50 loc) · 1.37 KB
/
scratch.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 { E } from '@endo/eventual-send';
import { Far } from '@endo/marshal';
export default function makeScratchPad() {
const map = new Map();
const keys = async () => {
const keyList = [...map.keys()];
return harden(keyList.sort());
};
const scratch = Far('scratchPad', {
delete: async keyP => {
const key = await keyP;
map.delete(key);
},
get: async keyP => {
const key = await keyP;
return map.get(key);
},
lookup: (...path) => {
if (path.length === 0) {
return scratch;
}
const [first, ...rest] = path;
const firstValue = E(scratch).get(first);
if (rest.length === 0) {
return firstValue;
}
return E(firstValue).lookup(...rest);
},
// Initialize a key only if it doesn't already exist. Needed for atomicity
// between multiple invocations.
init: async (keyP, objP) => {
const [key, obj] = await Promise.all([keyP, objP]);
if (map.has(key)) {
throw Error(`Scratchpad already has key ${key}`);
}
map.set(key, obj);
return key;
},
keys,
// Legacy alias for `keys`.
list: keys,
set: async (keyP, objP) => {
const [key, obj] = await Promise.all([keyP, objP]);
map.set(key, obj);
return key;
},
});
return scratch;
}
/** @typedef {ReturnType<typeof makeScratchPad>} ScratchPad */