简体   繁体   中英

Random numbers stream with Bacon.js

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM