Files: ae89aab540caa1cee5f40dcc78fc2210e40b024e / dict-to-collection.js
1451 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 | |
7 | module.exports = function DictToCollection (obs) { |
8 | var value = [] |
9 | var raw = [] |
10 | |
11 | var instance = computed.extended(obs, function () { |
12 | var keys = getKeys(obs) |
13 | var length = keys.length |
14 | |
15 | for (var i = 0; i < length; i++) { |
16 | var key = keys[i] |
17 | var item = obs.get(key) |
18 | if (shouldUpdate(item, raw[i])) { |
19 | if (raw[i].key() !== key) { |
20 | raw[i].key.set(key) |
21 | } |
22 | if (raw[i].value !== item) { |
23 | raw[i].value.set(item) |
24 | } |
25 | } else { |
26 | raw[i] = KeyValue(key, item) |
27 | } |
28 | value[i] = resolve(raw[i]) |
29 | } |
30 | |
31 | raw.length = value.length = length |
32 | return value |
33 | }) |
34 | |
35 | var result = function MutantDictToCollection (listener) { |
36 | return instance(listener) |
37 | } |
38 | |
39 | // getLength, get, indexOf, etc |
40 | addCollectionMethods(result, raw, instance.checkUpdated) |
41 | |
42 | return result |
43 | } |
44 | |
45 | function shouldUpdate (newItem, keyValue) { |
46 | if (!keyValue) { |
47 | return false |
48 | } else if (isObservable(newItem) && keyValue.value === newItem) { |
49 | return true |
50 | } else { |
51 | return !keyValue.isBound |
52 | } |
53 | } |
54 | |
55 | function getKeys (value) { |
56 | if (isObservable(value) && value.keys) { |
57 | return resolve(value.keys) |
58 | } else { |
59 | return Object.keys(resolve(value)) |
60 | } |
61 | } |
62 |
Built with git-ssb-web