Random numbers stream with Bacon.js

270 Views Asked by At

I'm trying to dive in reactive programming. So I decided to create a simple chat with RSA encryption using Bacon javascript library.

The questions I have: What is the best way to create random numbers stream with Bacon? After it I want to filter random numbers stream to random primes stream. What is the best way to do this?

1

There are 1 best solutions below

5
On

I'm not sure Bacon streams are the right thing to use for this, but here's how you could do it.

function makeRandomNumber() {
  return Math.random();
}

function makeRandomStream() {
  return Bacon.fromBinder(function(sink) {
    while(sink(makeRandomNumber()) === Bacon.more) {}
    return function() {};
  });
}

// example of using the random stream
makeRandomStream().filter(function(x) {
  return x > 0.5;
}).take(5).onValue(function(x) {
  console.log('random number', x);
});

Note that makeRandomStream() returns a new Bacon stream each time. You most likely don't want to attach multiple subscribers to the same random number stream or else you'll be re-using the same random numbers in multiple places. Also make sure that you always unsubscribe from the random number stream synchronously; don't try to combine it with another stream first, or else the random number stream will block the rest of the code from running as it generates unlimited random numbers.

And you'll want to use window.crypto.getRandomValues instead of Math.random for cryptographic uses.