简体   繁体   English

Bacon.js随机流

[英]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. 因此,我决定使用Bacon javascript库使用RSA加密创建简单的聊天记录。

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. 注意,makeRandomStream()每次都会返回一个新的Bacon流。 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. 而且,您将希望使用window.crypto.getRandomValues而不是Math.random进行加密。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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