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