【发布时间】:2019-04-22 12:46:04
【问题描述】:
我想实现一个可以做到这一点的流对象:
// a -------1------2----3
// map -----\------\----\
// b --------2------4----6
const a = new Stream();
const b = a.map(value => value * 2);
b.subscribe(console.log);
a.push(1);
// 2
a.push(2);
// 4
a.push(3);
// 6
这里的想法是对象b 可以订阅新的回调到流a。 map 函数应该在调用 push 时进行监听,并应用映射出的函数以及最初订阅的函数。这是我到目前为止的实现:
class Stream {
constructor(queue = []) {
this.queue = queue;
}
subscribe(action) {
if (typeof action === 'function') {
this.queue.push(action);
}
}
map(callback) {
this.queue = this.queue.map(
actionFn => arg => action(callback(arg))
);
return this;
}
push(value) {
this.queue.forEach(actionFn => {
actionFn.call(this, value);
});
}
}
当前实现的问题是,最初类 Stream 中的 queue 是空的,所以它不会通过它。将不胜感激任何建议或帮助。我不想为此使用任何库。
【问题讨论】:
标签: javascript node.js stream