Files: 1bfc5e6fd4a84f660a134de905aff9b599e108f3 / dict-to-collection.js
1375 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].value !== item) { |
20 | raw[i].value.set(item) |
21 | } |
22 | } else { |
23 | raw[i] = KeyValue(key, item) |
24 | } |
25 | value[i] = resolve(raw[i]) |
26 | } |
27 | |
28 | raw.length = value.length = length |
29 | return value |
30 | }) |
31 | |
32 | var result = function MutantDictToCollection (listener) { |
33 | return instance(listener) |
34 | } |
35 | |
36 | // getLength, get, indexOf, etc |
37 | addCollectionMethods(result, raw, instance.checkUpdated) |
38 | |
39 | return result |
40 | } |
41 | |
42 | function shouldUpdate (newItem, keyValue) { |
43 | if (!keyValue) { |
44 | return false |
45 | } else if (isObservable(newItem) && keyValue.value === newItem) { |
46 | return true |
47 | } else { |
48 | return !keyValue.isBound |
49 | } |
50 | } |
51 | |
52 | function getKeys (value) { |
53 | if (isObservable(value) && value.keys) { |
54 | return resolve(value.keys) |
55 | } else { |
56 | return Object.keys(resolve(value)) |
57 | } |
58 | } |
59 |
Built with git-ssb-web