git ssb

1+

Matt McKegg / mutant



Commit be0df157d2e308a5ea7014d2d266d2d48f87699d

add keys and watch-all helpers

Matt McKegg committed on 7/21/2016, 4:11:26 AM
Parent: 5dfdb498b7d97dce1f07169d43146aa777dd3431

Files changed

keys.jsadded
watch-all.jsadded
keys.jsView
@@ -1,0 +1,30 @@
1 +var computed = require('./computed')
2 +
3 +module.exports = Keys
4 +
5 +function Keys (collection) {
6 + var result = []
7 + var initialized = false
8 + return computed(collection, function (value) {
9 + var keys = Object.keys(value)
10 + var changed = false
11 + for (var i = 0; i < keys.length; i++) {
12 + if (result[i] !== keys[i]) {
13 + result[i] = keys[i]
14 + changed = true
15 + }
16 + }
17 +
18 + if (result.length !== keys.length) {
19 + changed = true
20 + result.length = keys.length
21 + }
22 +
23 + if (changed || !initialized) {
24 + initialized = true
25 + return result
26 + } else {
27 + return computed.NO_CHANGE
28 + }
29 + })
30 +}
watch-all.jsView
@@ -1,0 +1,34 @@
1 +var resolve = require('./resolve')
2 +var isObservable = require('./is-observable')
3 +
4 +module.exports = watchAll
5 +
6 +function watchAll (observables, listener) {
7 + if (!Array.isArray(observables)) {
8 + observables = [ observables ]
9 + }
10 +
11 + var releases = observables.map(bind, broadcast)
12 + broadcast()
13 +
14 + return function () {
15 + releases.forEach(tryInvoke)
16 + releases.length = 0
17 + }
18 +
19 + function broadcast () {
20 + listener.apply(this, observables.map(resolve))
21 + }
22 +}
23 +
24 +function bind (value) {
25 + if (isObservable(value)) {
26 + return value(this)
27 + }
28 +}
29 +
30 +function tryInvoke (value) {
31 + if (typeof value === 'function') {
32 + return value()
33 + }
34 +}

Built with git-ssb-web