-
Notifications
You must be signed in to change notification settings - Fork 11
/
lookup.js
78 lines (66 loc) · 1.87 KB
/
lookup.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
78
var MutantMap = require('./map')
var computed = require('./computed')
var resolve = require('./resolve')
var KeyValue = require('./lib/key-value')
var isObservable = require('./is-observable')
module.exports = Lookup
function Lookup (obs, lambdaOrKey, opts) {
var mapped = MutantMap(obs, function (item, invalidateOn) {
if (typeof lambdaOrKey === 'function') {
var value = lambdaOrKey(item, invalidateOn)
if (isObservable(value) && value._type === 'MutantKeyValue') {
return value // passthru
} else if (Array.isArray(value)) {
return KeyValue(value[0], value[1])
} else if (value != null) {
return KeyValue(value, item)
}
} else if (typeof lambdaOrKey === 'string') {
return KeyValue(item[lambdaOrKey], item)
}
})
var raw = {}
var value = {}
var keys = new Set()
var instance = computed.extended(mapped, function update () {
var currentKeys = []
for (var i = 0; i < mapped.getLength(); i++) {
var item = mapped.get(i)
if (item) {
var key = resolve(item.key)
if (key != null) {
var rawValue = item.value
currentKeys.push(key)
keys.add(key)
raw[key] = rawValue
value[key] = resolve(rawValue)
}
}
}
// remove deleted keys
Array.from(keys.values()).filter(function (k) {
return !currentKeys.includes(k)
}).forEach(function (key) {
keys.delete(key)
delete raw[key]
delete value[key]
})
return value
})
var result = function MutantLookup (listener) {
return instance(listener)
}
result.keys = function () {
instance.checkUpdated()
return Array.from(keys.values())
}
result.get = function (key) {
instance.checkUpdated()
return raw[key]
}
result.has = function (key) {
instance.checkUpdated()
return key in raw
}
return result
}