Files: 8b3e0bbdac89aa4cd743500d35bbd504bd7a49b7 / lib / sustained.js
917 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)) { // 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