Files: 69876840cadd2230cb5947b124fbec64d7846258 / lib / sustained.js
978 bytesRaw
1 | var watch = require('mutant/watch') |
2 | var computed = require('mutant/computed') |
3 | var Value = require('mutant/value') |
4 | |
5 | module.exports = Sustained |
6 | |
7 | // only broadcast value changes once a truthy value has stayed constant for more than timeThreshold |
8 | |
9 | function 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