git ssb

1+

Matt McKegg / mutant



Tree: 4f9e58ce423d145b70980a342e93dbbffbbc95f6

Files: 4f9e58ce423d145b70980a342e93dbbffbbc95f6 / dict-to-collection.js

1633 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')
6var MutantMap = require('./map')
7
8module.exports = DictToCollection
9
10function 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
48module.exports.values = function (obs) {
49 return MutantMap(DictToCollection(obs), function (item) {
50 return item.value
51 })
52}
53
54function 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
64function 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