git ssb

1+

Matt McKegg / mutant



Tree: 2225e7077f112ee10318157443adbbdb5748a50e

Files: 2225e7077f112ee10318157443adbbdb5748a50e / set.js

2203 bytesRaw
1var Value = require('./value')
2
3module.exports = Set
4
5function 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.destroy = observable.clear
64
65 return observable
66
67 function refresh () {
68 update()
69 broadcast(object)
70 }
71
72 function update () {
73 var currentValues = object.map(get)
74 var newValues = sources.map(resolve)
75 currentValues.filter(notIncluded, newValues).forEach(removeFrom, object)
76 newValues.filter(notIncluded, currentValues).forEach(addTo, object)
77 }
78}
79
80function get (value) {
81 return value
82}
83
84function resolve (source) {
85 return typeof source === 'function' ? source() : source
86}
87
88function notIncluded (value) {
89 return !~this.indexOf(value)
90}
91
92function removeFrom (item) {
93 var index = this.indexOf(item)
94 if (~index) {
95 this.splice(index, 1)
96 }
97}
98
99function addTo (item) {
100 this.push(item)
101}
102
103function tryInvoke (func) {
104 if (typeof func === 'function') {
105 func()
106 }
107}
108

Built with git-ssb-web