git ssb

1+

Daan Patchwork / patchwork



Tree: 612509945be4d8cb719d3b0a5a0390a0ddbcf911

Files: 612509945be4d8cb719d3b0a5a0390a0ddbcf911 / lib / sustained.js

990 bytesRaw
1const watch = require('mutant/watch')
2const computed = require('mutant/computed')
3const 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 const outputValue = Value(obs())
11 let lastValue = null
12 let 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 const delay = typeof timeThreshold === 'function' ? timeThreshold(value, outputValue()) : timeThreshold
25 timer = setTimeout(update, delay)
26 }
27 lastValue = value
28 }
29
30 function update () {
31 const value = obs()
32 if (value !== outputValue()) {
33 outputValue.set(value)
34 }
35 }
36}
37

Built with git-ssb-web