git ssb

10+

Matt McKegg / patchwork



Tree: fca7e884b005b72ad936e12d9186829ea5e7d0df

Files: fca7e884b005b72ad936e12d9186829ea5e7d0df / lib / sustained.js

978 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)) {
20 clearTimeout(timer)
21 update()
22 } else if (value !== lastValue) {
23 clearTimeout(timer)
24 var delay = typeof timeThreshold === 'function' ? timeThreshold(value, outputValue()) : timeThreshold
25 timer = setTimeout(update, delay)
26 }
27 lastValue = value
28 }
29
30 function update () {
31 var value = obs()
32 if (value !== outputValue()) {
33 outputValue.set(value)
34 }
35 }
36}
37

Built with git-ssb-web