Files: 4c817e4a9ce3c28a60cc7547029ee43eb9d9f909 / merge.js
1476 bytesRaw
1 | var computed = require('./computed') |
2 | var resolve = require('./resolve') |
3 | var isObservable = require('./is-observable') |
4 | |
5 | module.exports = Merge |
6 | |
7 | function Merge (sources) { |
8 | var raw = {} |
9 | var value = {} |
10 | var keys = new Set() |
11 | |
12 | var instance = computed.extended(sources, function update () { |
13 | var currentKeys = [] |
14 | |
15 | forEach(sources, function (source) { |
16 | forEachPair(source, function (key, rawValue) { |
17 | currentKeys.push(key) |
18 | keys.add(key) |
19 | raw[key] = rawValue |
20 | value[key] = resolve(rawValue) |
21 | }) |
22 | }) |
23 | |
24 | // remove deleted keys |
25 | Array.from(keys.values()).filter(function (k) { |
26 | return !currentKeys.includes(k) |
27 | }).forEach(function (key) { |
28 | keys.delete(key) |
29 | delete raw[key] |
30 | delete value[key] |
31 | }) |
32 | |
33 | return value |
34 | }) |
35 | |
36 | var result = function MutantMerge (listener) { |
37 | return instance(listener) |
38 | } |
39 | |
40 | result.keys = function () { |
41 | instance.checkUpdated() |
42 | return Array.from(keys.values()) |
43 | } |
44 | |
45 | result.get = function (key) { |
46 | instance.checkUpdated() |
47 | return raw[key] |
48 | } |
49 | |
50 | return result |
51 | } |
52 | |
53 | function forEach (sources, fn) { |
54 | if (sources && !sources.forEach) { |
55 | sources = resolve(sources) |
56 | } |
57 | |
58 | if (sources && sources.forEach) { |
59 | sources.forEach(fn) |
60 | } |
61 | } |
62 | |
63 | function forEachPair (source, fn) { |
64 | if (source) { |
65 | if (isObservable(source) && source.keys && source.get) { |
66 | resolve(source.keys).forEach(function (key) { |
67 | fn(key, source.get(key)) |
68 | }) |
69 | } |
70 | } |
71 | } |
72 |
Built with git-ssb-web