git ssb

10+

Matt McKegg / patchwork



Tree: 42288cf44aa8aaf32d1036942ee30c6730803575

Files: 42288cf44aa8aaf32d1036942ee30c6730803575 / lib / sustained.js

917 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 var timer = null
13
14 return computed(outputValue, v => v, {
15 onListen: () => watch(obs, onChange)
16 })
17
18 function onChange (value) {
19 if (checkUpdateImmediately && checkUpdateImmediately(value)) { // update immediately for falsy values
20 clearTimeout(timer)
21 update()
22 } else if (value !== lastValue) {
23 clearTimeout(timer)
24 timer = setTimeout(update, timeThreshold)
25 }
26 lastValue = value
27 }
28
29 function update () {
30 var value = obs()
31 if (value !== outputValue()) {
32 outputValue.set(value)
33 }
34 }
35}
36

Built with git-ssb-web