Reputation: 692
From my understanding of FRP, we should use pure functions which means that the input is not mutated. How do I create a pure function which relies on the previous value?
For example, I have an object which moves horizontally every time I press the space key. This means that the x value needs to be updated based on the previous x value.
Initially, object starts at x -> 0. Pressed space key, x -> 1. Pressed space key again, x -> 2.
If we are not allowed to mutate the value of x like this (javascript code),
let x = 0;
function set_x() {
x += 1;
}
how can my program remember what the previous value of x is?
Upvotes: 0
Views: 89
Reputation: 370367
Generally FRP works by creating one stream from another using higher-order functions. When you need the previous value of the stream, the function you want is going to be called fold
, reduce
or scan
. It takes an event stream, a starting value and function and produces another stream that starts with the starting value and then takes the result of f(p, x)
(where p
is the previous value of the new stream and x
the current value of the original stream) every time there's an event on the original stream.
For example, in Bacon.JS the method you want is called scan
(fold
also exists, but only emits the final value, so doesn't do what we want here) and your code could look like this:
const numberOfSpacePresses = spacePressEvents.scan(0, (count, _) => count + 1);
Some libraries may also already have a function or method named count
that does what you want, so you could just write spacePressEvents.count()
.
Upvotes: 2