gpt4 book ai didi

javascript - 匹配 `reduce/scan` 的累加器函数中的可观察类型?

转载 作者:行者123 更新时间:2023-11-29 21:42:45 24 4
gpt4 key购买 nike

我想将我的应用程序状态写成reduce(或者更确切地说是 scan)对所有输入可观察量的函数。

const inputStream$ =
Rx.Observable.merge(all$, observables$, Im$, interested$, in$);

const outputStream$ = inputStream$.scan(accumulator, initialState);

由于 inputStream$ 可以包含任何值,因此 accumulator 函数将不得不做很多看起来相当脆弱的类型检查。

我正在寻找的是这样的东西:

function accumulator (acc, x) {
switch (x) {
case "all$ has fired":
return newState0;
case "observables$ has fired":
return newState1;
case "Im$ has fired":
return newState2;
case "interested$ has fired":
return newState3;
case "in$ has fired":
return newState4;

}

这可能吗?

最佳答案

当然。只需将 map 运算符应用于每个输入流,以便在合并之前向值添加鉴别器:

Rx.Observable.prototype.tag = function (tag) {
return this.map(value => ({ tag, value }));
};

const inputStream$ = Rx.Observable.merge(a.tag("a"), b.tag("b"), ...);
const outputStream$ = inputStream$.scan(v => {
const value = v.value;
switch (v.tag) {
case "a": return newState0;
case "b": return newState1;
...
}
}, initialState);

关于javascript - 匹配 `reduce/scan` 的累加器函数中的可观察类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32186726/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com