git ssb

1+

Matt McKegg / mutant



Tree: 56963dca8e160319d630c173c0f3b003996ae919

Files: 56963dca8e160319d630c173c0f3b003996ae919 / dict-to-collection.js

1375 bytesRaw
1var addCollectionMethods = require('./lib/add-collection-methods')
2var computed = require('./computed')
3var KeyValue = require('./lib/key-value')
4var resolve = require('./resolve')
5var isObservable = require('./is-observable')
6
7module.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
42function 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
52function 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