gpt4 book ai didi

functional-programming - 创建一个通过过滤器的连续值流

转载 作者:行者123 更新时间:2023-12-04 02:00:34 24 4
gpt4 key购买 nike

假设我有一个数字流

---1-----1----1----0----0----1----1----0---->

我想得到一个新的数组流,其中包含像这样的连续 1

---[1,1,1]---[1,1]--->

我虽然使用了扫描函数,但它只发出一个值,我阅读了有关 bufferToggle 的信息,但文档只将它与定时可观察对象一起使用。有什么功能可以做到这一点吗?

最佳答案

一种可能的方法是使用 scanpairwise 运算符。

使用成对的方法,您可以将第 N-1 次发射与第 N 次发射进行比较。

console.clear();
var source = Rx.Observable.of(1, 1, 1, 0, 0, 1, 1, 0);

source
.concat(Rx.Observable.of(0)) // for the case when source completes with 1
.scan(function(acc, x) {
// reset accumulator to an empty array when a 0 is encountered
if (x === 0) {
return [];
} else {
return acc.concat([x]);
}
}, [])
.pairwise()
// filter when the accumulated value goes from a length greater than 0
// to 0 then you know you've hit 0
.filter((pair) => pair[0].length > 0 && pair[1].length === 0)
// take the first element of the pair since it has the result you're interested in
.map((pair) => pair[0])
.subscribe(console.log)
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.0.2/Rx.min.js"></script>

关于functional-programming - 创建一个通过过滤器的连续值流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47543177/

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