Files: 01e9e1d516a0bcf09d486425ab7cba0f919f5a1a / dict-to-collection.js
2148 bytesRaw
1 | var addCollectionMethods = require('./lib/add-collection-methods') |
2 | var computed = require('./computed') |
3 | var KeyValue = require('./lib/key-value') |
4 | var resolve = require('./resolve') |
5 | var isObservable = require('./is-observable') |
6 | var MutantMap = require('./map') |
7 | |
8 | module.exports = DictToCollection |
9 | |
10 | function DictToCollection (obs) { |
11 | var value = [] |
12 | var raw = [] |
13 | var keys = [] |
14 | |
15 | var instance = computed.extended(obs, function () { |
16 | var newKeys = getKeys(obs) |
17 | var remove = keys.filter((key) => !newKeys.includes(key)) |
18 | var add = newKeys.filter((key) => !keys.includes(key)) |
19 | var update = keys.filter((key) => keys.includes(key)) |
20 | |
21 | remove.forEach((key) => { |
22 | var index = keys.indexOf(key) |
23 | if (~index) { |
24 | keys.splice(index, 1) |
25 | raw.splice(index, 1) |
26 | value.splice(index, 1) |
27 | } |
28 | }) |
29 | |
30 | add.forEach((key) => { |
31 | var item = getValue(obs, key) |
32 | var rawValue = KeyValue(key, item) |
33 | keys.push(key) |
34 | raw.push(rawValue) |
35 | value.push(resolve(rawValue)) |
36 | }) |
37 | |
38 | update.forEach((key) => { |
39 | var index = keys.indexOf(key) |
40 | if (~index) { |
41 | var item = getValue(obs, key) |
42 | if (raw[index].isBound || isObservable(item)) { |
43 | if (raw[index].value !== item) { |
44 | raw[index] = KeyValue(key, item) |
45 | } |
46 | } else { |
47 | raw[index].value.set(item) |
48 | } |
49 | value[index] = resolve(raw[index]) |
50 | } |
51 | }) |
52 | |
53 | return value |
54 | }) |
55 | |
56 | var result = function MutantDictToCollection (listener) { |
57 | return instance(listener) |
58 | } |
59 | |
60 | // getLength, get, indexOf, etc |
61 | addCollectionMethods(result, raw, instance.checkUpdated) |
62 | |
63 | return result |
64 | } |
65 | |
66 | module.exports.values = function (obs) { |
67 | return MutantMap(DictToCollection(obs), function (item) { |
68 | return item.value |
69 | }) |
70 | } |
71 | |
72 | function getKeys (value) { |
73 | if (isObservable(value) && value.keys) { |
74 | return resolve(value.keys) |
75 | } else { |
76 | return Object.keys(resolve(value)) |
77 | } |
78 | } |
79 | |
80 | function getValue (obj, key) { |
81 | if (isObservable(obj) && obj.get) { |
82 | return obj.get(key) |
83 | } else { |
84 | var resolved = resolve(obj) |
85 | if (resolved) { |
86 | return resolved[key] |
87 | } |
88 | } |
89 | } |
90 |
Built with git-ssb-web