0

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?

gyzerok
  • 1,338
  • 2
  • 11
  • 26

1 Answers1

1

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.

Macil
  • 3,575
  • 1
  • 20
  • 18
  • What if I'd try to combine some stream got by mapping this stream with other streams? – gyzerok Dec 02 '14 at 05:50
  • gyzerok: if you have a concrete example, maybe a jsFiddle, it would be easier to help. I'm having trouble finding a concrete use case for this stream. – OlliM Dec 02 '14 at 09:26
  • https://github.com/gyzerok/reactive-cryptochat/blob/master/rsa.js There i'm using this stream to generate e, d and m values for my rsa chat application. Thank you for helping me. – gyzerok Dec 02 '14 at 10:12
  • 2
    As I read your application correctly, you use a great number of Bacon streams in order to create a single object with e, d and m. That means that you could just calculate those values normally and put the result inside a `Bacon.constant` - no need for FRP. Although I guess you're just using this as an exercise, so your implementation looks fine. The only style difference is that I would extract your combinator and filter functions into nicely named functions, in order to have a clearer overview of the flow of data. – OlliM Dec 02 '14 at 10:31
  • Yes, I'm making this for practice purposes. Thanks for your advises and code review. – gyzerok Dec 02 '14 at 11:05