Files: 7f33edf4e20870b7b514970eda78bcfeb2791a11 / set.js
2342 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.get = function (index) { |
64 | return sources[index] |
65 | } |
66 | |
67 | observable.getLength = function () { |
68 | return sources.length |
69 | } |
70 | |
71 | observable.destroy = observable.clear |
72 | |
73 | return observable |
74 | |
75 | function refresh () { |
76 | update() |
77 | broadcast(object) |
78 | } |
79 | |
80 | function update () { |
81 | var currentValues = object.map(get) |
82 | var newValues = sources.map(resolve) |
83 | currentValues.filter(notIncluded, newValues).forEach(removeFrom, object) |
84 | newValues.filter(notIncluded, currentValues).forEach(addTo, object) |
85 | } |
86 | } |
87 | |
88 | function get (value) { |
89 | return value |
90 | } |
91 | |
92 | function resolve (source) { |
93 | return typeof source === 'function' ? source() : source |
94 | } |
95 | |
96 | function notIncluded (value) { |
97 | return !~this.indexOf(value) |
98 | } |
99 | |
100 | function removeFrom (item) { |
101 | var index = this.indexOf(item) |
102 | if (~index) { |
103 | this.splice(index, 1) |
104 | } |
105 | } |
106 | |
107 | function addTo (item) { |
108 | this.push(item) |
109 | } |
110 | |
111 | function tryInvoke (func) { |
112 | if (typeof func === 'function') { |
113 | func() |
114 | } |
115 | } |
116 |
Built with git-ssb-web