Search code examples
javascriptfrpbacon.js

Implement a numeric spinner in Bacon.js


There is a text field and two buttons, (+) and (-). It is trivial to get a value from button clicks:

// provided plusStream contains +1 for each (+) click
// and minusStream -1 for each (-) click.
let value = plusStream.merge(minusStream).scan(0, (a, b) => a + b);

The question is, how to handle directChange stream which contains a number for each valid change of the text field?

It should alter the value somehow. Moreover the .scan() should be aware of the change so that next button click addis or subtracts 1 from the updated value.


Solution

  • I suggest you try Bacon.update. This might work:

    Bacon.update(0,
      plusStream, (prev) => prev + 1,
      minusStream, (prev) => prev - 1,
      directChangeStream, (prev, updated) => updated
    )