forked from openhab/openhab-js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcache.js
77 lines (71 loc) · 2.29 KB
/
cache.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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
/**
* Shared cache namespace.
* This namespace provides a default cache that can be used to set and retrieve objects that will be persisted between reloads of scripts.
*
* @namespace cache
*/
const cache = require('@runtime').sharedcache;
/**
* Returns the value to which the specified key is mapped
*
* @example <caption>Get a previously set value with a default value (times = 0)</caption>
* let counter = cache.get("counter", () => ({ "times": 0 }));
* console.log("Count",counter.times++);
*
* @example <caption>Get a previously set object</caption>
* let counter = cache.get("counter");
* if(counter == null){
* counter = {times: 0};
* cache.put("counter", counter);
* }
* console.log("Count",counter.times++);
*
* @memberof cache
* @param {string} key the key whose associated value is to be returned
* @param {function} [defaultSupplier] if the specified key is not already associated with a value, this function will return a default value
* @returns {(*|null)} the current object for the supplied key, a default value if defaultSupplier is provided, or null
*/
const get = function (key, defaultSupplier) {
if (typeof defaultSupplier === 'function') {
return cache.get(key, defaultSupplier);
} else {
return cache.get(key);
}
};
/**
* Associates the specified value with the specified key
*
* @memberof cache
* @param {string} key key with which the specified value is to be associated
* @param {*} value value to be associated with the specified key
* @returns {(*|null)} the previous value associated with null, or null if there was no mapping for key
*/
const put = function (key, value) {
return cache.put(key, value);
};
/**
* Removes the mapping for a key from this map if it is present
*
* @memberof cache
* @param {string} key key whose mapping is to be removed from the map
* @returns {(*|null)} the previous value associated with key or null if there was no mapping for key
*/
const remove = function (key) {
return cache.remove(key);
};
/**
* Checks the mapping for a key from this map.
*
* @memberof cache
* @param {string} key key whose mapping is to be checked in the map
* @returns {boolean} whether the key has a mapping
*/
const exists = function (key) {
return get(key) !== null;
};
module.exports = {
get,
put,
remove,
exists
};