Files: b715609f8d6393dc7cf2fa7be33b256bffcce3e3 / set.js
2273 bytesRaw
1 | var Value = require('./value') |
2 | |
3 | module.exports = Set |
4 | |
5 | function Set (defaultValues) { |
6 | var object = [] |
7 | var sources = [] |
8 | var releases = [] |
9 | |
10 | if (defaultValues && defaultValues.length) { |
11 | defaultValues.forEach(function (valueOrObs) { |
12 | if (!~sources.indexOf(valueOrObs)) { |
13 | sources.push(valueOrObs) |
14 | releases[sources.length - 1] = typeof valueOrObs === 'function' |
15 | ? valueOrObs(refresh) |
16 | : null |
17 | } |
18 | }) |
19 | update() |
20 | } |
21 | |
22 | var observable = Value(object) |
23 | var broadcast = observable.set |
24 | |
25 | observable.add = function (valueOrObs) { |
26 | if (!~sources.indexOf(valueOrObs)) { |
27 | sources.push(valueOrObs) |
28 | releases[sources.length - 1] = typeof valueOrObs === 'function' |
29 | ? valueOrObs(refresh) |
30 | : null |
31 | refresh() |
32 | } |
33 | } |
34 | |
35 | observable.clear = function () { |
36 | releases.forEach(tryInvoke) |
37 | sources.length = 0 |
38 | releases.length = 0 |
39 | refresh() |
40 | } |
41 | |
42 | observable.delete = function (valueOrObs) { |
43 | var index = sources.indexOf(valueOrObs) |
44 | if (~index) { |
45 | sources.splice(index, 1) |
46 | releases.splice(index, 1).forEach(tryInvoke) |
47 | refresh() |
48 | } |
49 | } |
50 | |
51 | observable.has = function (valueOrObs) { |
52 | return !!~object.indexOf(valueOrObs) |
53 | } |
54 | |
55 | observable.set = function (values) { |
56 | sources.length = 0 |
57 | values.forEach(function (value) { |
58 | sources.push(value) |
59 | }) |
60 | refresh() |
61 | } |
62 | |
63 | observable.getLength = function () { |
64 | return sources.length |
65 | } |
66 | |
67 | observable.destroy = observable.clear |
68 | |
69 | return observable |
70 | |
71 | function refresh () { |
72 | update() |
73 | broadcast(object) |
74 | } |
75 | |
76 | function update () { |
77 | var currentValues = object.map(get) |
78 | var newValues = sources.map(resolve) |
79 | currentValues.filter(notIncluded, newValues).forEach(removeFrom, object) |
80 | newValues.filter(notIncluded, currentValues).forEach(addTo, object) |
81 | } |
82 | } |
83 | |
84 | function get (value) { |
85 | return value |
86 | } |
87 | |
88 | function resolve (source) { |
89 | return typeof source === 'function' ? source() : source |
90 | } |
91 | |
92 | function notIncluded (value) { |
93 | return !~this.indexOf(value) |
94 | } |
95 | |
96 | function removeFrom (item) { |
97 | var index = this.indexOf(item) |
98 | if (~index) { |
99 | this.splice(index, 1) |
100 | } |
101 | } |
102 | |
103 | function addTo (item) { |
104 | this.push(item) |
105 | } |
106 | |
107 | function tryInvoke (func) { |
108 | if (typeof func === 'function') { |
109 | func() |
110 | } |
111 | } |
112 |
Built with git-ssb-web