CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
sagemathinc

Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.

GitHub Repository: sagemathinc/cocalc
Path: blob/master/src/packages/util/key-value-store.js
Views: 687
1
/*
2
* This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.
3
* License: MS-RSL – see LICENSE.md for details
4
*/
5
6
/*
7
Very, very simple key:value store.
8
9
The keys can be arbitrary json-able objects.
10
A frozen copy of the object is saved in the key:value store,
11
so it won't get mutated.
12
*/
13
14
const json = require("json-stable-stringify");
15
16
exports.key_value_store = () => new KeyValueStore();
17
18
class KeyValueStore {
19
constructor() {
20
this.set = this.set.bind(this);
21
this.get = this.get.bind(this);
22
this.delete = this.delete.bind(this);
23
this.close = this.close.bind(this);
24
this._data = {};
25
}
26
27
assert_not_closed() {
28
if (this._data == null) {
29
throw Error("closed -- KeyValueStore");
30
}
31
}
32
33
set(key, value) {
34
this.assert_not_closed();
35
if (value.freeze != null) {
36
// supported by modern browsers
37
value = value.freeze(); // so doesn't get mutated
38
}
39
this._data[json(key)] = value;
40
}
41
42
get(key) {
43
this.assert_not_closed();
44
return this._data[json(key)];
45
}
46
47
delete(key) {
48
this.assert_not_closed();
49
delete this._data[json(key)];
50
}
51
52
close() {
53
delete this._data;
54
}
55
}
56
57