Files: 70bdc654bff8ac23d9006bcbee7a5fa93d8abf62 / lookup.js
1915 bytesRaw
1 | var MutantMap = require('./map') |
2 | var computed = require('./computed') |
3 | var resolve = require('./resolve') |
4 | var KeyValue = require('./lib/key-value') |
5 | var isObservable = require('./is-observable') |
6 | |
7 | module.exports = Lookup |
8 | |
9 | function Lookup (obs, lambdaOrKey, opts) { |
10 | var mapped = MutantMap(obs, function (item, invalidateOn) { |
11 | if (typeof lambdaOrKey === 'function') { |
12 | var value = lambdaOrKey(item, invalidateOn) |
13 | if (isObservable(value) && value._type === 'MutantKeyValue') { |
14 | return value // passthru |
15 | } else if (Array.isArray(value)) { |
16 | return KeyValue(value[0], value[1]) |
17 | } else if (value != null) { |
18 | return KeyValue(value, item) |
19 | } |
20 | } else if (typeof lambdaOrKey === 'string') { |
21 | return KeyValue(item[lambdaOrKey], item) |
22 | } |
23 | }) |
24 | |
25 | var raw = {} |
26 | var value = {} |
27 | var keys = new Set() |
28 | |
29 | var instance = computed.extended(mapped, function update () { |
30 | var currentKeys = [] |
31 | |
32 | for (var i = 0; i < mapped.getLength(); i++) { |
33 | var item = mapped.get(i) |
34 | if (item) { |
35 | var key = resolve(item.key) |
36 | if (key != null) { |
37 | var rawValue = item.value |
38 | currentKeys.push(key) |
39 | keys.add(key) |
40 | raw[key] = rawValue |
41 | value[key] = resolve(rawValue) |
42 | } |
43 | } |
44 | } |
45 | |
46 | // remove deleted keys |
47 | Array.from(keys.values()).filter(function (k) { |
48 | return !currentKeys.includes(k) |
49 | }).forEach(function (key) { |
50 | keys.delete(key) |
51 | delete raw[key] |
52 | delete value[key] |
53 | }) |
54 | |
55 | return value |
56 | }) |
57 | |
58 | var result = function MutantLookup (listener) { |
59 | return instance(listener) |
60 | } |
61 | |
62 | result.keys = function () { |
63 | instance.checkUpdated() |
64 | return Array.from(keys.values()) |
65 | } |
66 | |
67 | result.get = function (key) { |
68 | instance.checkUpdated() |
69 | return raw[key] |
70 | } |
71 | |
72 | result.has = function (key) { |
73 | instance.checkUpdated() |
74 | return key in raw |
75 | } |
76 | |
77 | return result |
78 | } |
79 |
Built with git-ssb-web