git ssb

0+

alanz / patchwork



forked from Matt McKegg / patchwork

Tree: 461fd4459a46469a272bb9fe6c369b1dd1c9323c

Files: 461fd4459a46469a272bb9fe6c369b1dd1c9323c / lib / sustained.js

882 bytesRaw
1var watch = require('mutant/watch')
2var computed = require('mutant/computed')
3var Value = require('mutant/value')
4
5module.exports = Sustained
6
7// only broadcast value changes once a truthy value has stayed constant for more than timeThreshold
8
9function Sustained (obs, timeThreshold, checkUpdateImmediately) {
10 var outputValue = Value(obs())
11 var lastValue = null
12
13 return computed(outputValue, v => v, {
14 onListen: () => watch(obs, onChange)
15 })
16
17 function onChange (value) {
18 if (checkUpdateImmediately && checkUpdateImmediately(value)) { // update immediately for falsy values
19 clearTimeout()
20 update()
21 } else if (value !== lastValue) {
22 clearTimeout()
23 setTimeout(update, timeThreshold)
24 lastValue = value
25 }
26 }
27
28 function update () {
29 var value = obs()
30 if (value !== outputValue()) {
31 outputValue.set(value)
32 }
33 }
34}
35

Built with git-ssb-web