我有一个创建随机整数的函数,但我试图重构它来创建随机加法表达式。它目前只生成单个整数。然后,消费者需要记录生产者正在进行的随机表达式的总和。这是一个工作关闭这个老github。https://github.com/ajlopez/SimpleQueue/blob/master/samples/ProducerConsumer/app.js
var sq = require('../..');
function getRandomInteger(from, to) {
return from + Math.floor(Math.random()*(to-from));
}
function Producer(queue, name) {
var n = 0;
var self = this;
this.process = function() {
console.log(name + ' generates ' + n);
var msg = n;
n++;
queue.putMessage(msg);
setTimeout(self.process, getRandomInteger(500, 1000));
}
}
//this should log
//Producer generates 5 + 9
//Second Producer generates 12 + 8
function Consumer(queue, name) {
var n = 0;
var self = this;
this.process = function() {
var msg = queue.getMessageSync();
if (msg != null)
console.log(name + ' process ' + msg);
setTimeout(self.process, getRandomInteger(300, 600));
}
}
//this should log the SUM of the 2 producers random expressions ie:
//Consumer process 5 + 9 = 14
//Consumer process 12 + 8 = 20
var producer = new Producer(queue, 'Producer');
var producer2 = new Producer(queue, 'Second Producer');
var consumer = new Consumer(queue, 'Consumer');
2条答案
按热度按时间monwx1rj1#
这将产生一个字符串表达式的结果,其数字在500到1000之间:
oaxa6hgo2#
如果你需要一个像这样的字符串'X + Y',然后加上引号,这样js就不会把两个随机数相加