Files: 3bfb6e65a932b5fb11b3c2260c7582699eb17ae5 / dict.js
2035 bytesRaw
1 | var Value = require('./value') |
2 | |
3 | module.exports = Dict |
4 | |
5 | function Dict (defaultValues) { |
6 | var object = Object.create({}) |
7 | var sources = [] |
8 | var releases = [] |
9 | |
10 | if (defaultValues) { |
11 | Object.keys(defaultValues).forEach(function (key) { |
12 | put(key, defaultValues[key]) |
13 | }) |
14 | } |
15 | |
16 | var observable = Value(object) |
17 | var broadcast = observable.set |
18 | |
19 | observable.put = function (key, valueOrObs) { |
20 | put(key, valueOrObs) |
21 | broadcast(object) |
22 | } |
23 | |
24 | observable.get = function (key) { |
25 | return sources[key] |
26 | } |
27 | |
28 | observable.keys = function () { |
29 | return Object.keys(sources) |
30 | } |
31 | |
32 | observable.clear = function () { |
33 | Object.keys(sources).forEach(function (key) { |
34 | tryInvoke(releases[key]) |
35 | delete sources[key] |
36 | delete releases[key] |
37 | delete object[key] |
38 | }) |
39 | broadcast(object) |
40 | } |
41 | |
42 | observable.delete = function (key) { |
43 | tryInvoke(releases[key]) |
44 | delete sources[key] |
45 | delete releases[key] |
46 | delete object[key] |
47 | broadcast(object) |
48 | } |
49 | |
50 | observable.includes = function (valueOrObs) { |
51 | return !!~object.indexOf(valueOrObs) |
52 | } |
53 | |
54 | observable.set = function (values) { |
55 | Object.keys(sources).forEach(function (key) { |
56 | tryInvoke(releases[key]) |
57 | delete sources[key] |
58 | delete releases[key] |
59 | delete object[key] |
60 | }) |
61 | |
62 | Object.keys(values).forEach(function (key) { |
63 | put(key, values[key]) |
64 | }) |
65 | |
66 | broadcast(object) |
67 | } |
68 | |
69 | observable.destroy = observable.clear |
70 | |
71 | return observable |
72 | |
73 | // scoped |
74 | |
75 | function put (key, valueOrObs) { |
76 | tryInvoke(releases[key]) |
77 | sources[key] = valueOrObs |
78 | releases[key] = bind(key, valueOrObs) |
79 | object[key] = resolve(valueOrObs) |
80 | } |
81 | |
82 | function bind (key, valueOrObs) { |
83 | return typeof valueOrObs === 'function' ? valueOrObs(update.bind(this, key)) : null |
84 | } |
85 | |
86 | function update (key, value) { |
87 | object[key] = value |
88 | broadcast(object) |
89 | } |
90 | } |
91 | |
92 | function resolve (source) { |
93 | return typeof source === 'function' ? source() : source |
94 | } |
95 | |
96 | function tryInvoke (func) { |
97 | if (typeof func === 'function') { |
98 | func() |
99 | } |
100 | } |
101 |
Built with git-ssb-web