-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
44 lines (38 loc) · 940 Bytes
/
index.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
module.exports = otv
function otv (generator, ttl) {
var store = new Map
value.verify = verify
value.expiry = expiry
return value
function value (key) {
return key != null ? (active(key) ?
store.get(key).value :
generate(key).value) :
null
}
function verify (key, value) {
return Boolean(active(key) &&
store.get(key).value === value &&
store.delete(key))
}
function expiry (key) {
return ttl &&
active(key) &&
(store.get(key).time + ttl) ||
null
}
function active (key) {
return key != null && Boolean(ttl ? (
store.has(key) &&
store.get(key).time != null &&
store.get(key).value != null &&
(Date.now() - store.get(key).time <= ttl)) :
(store.has(key) && store.get(key).value != null))
}
function generate (key) {
return store.set(key, {
time: Date.now(),
value: generator()
}).get(key)
}
}