git ssb

10+

Matt McKegg / patchwork



Tree: a6714b555b835f7ff3d98bee676b807e65593503

Files: a6714b555b835f7ff3d98bee676b807e65593503 / 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