gpt4 book ai didi

javascript - 如何使用函数式编程过滤多个路径

转载 作者:行者123 更新时间:2023-12-01 03:11:35 24 4
gpt4 key购买 nike

我有以下伪代码:

let array = getData();
array.filter(x => condition1(x)).doSomething1...
array.filter(x => condition2(x)).doSomething2...
array.filter(x => condition3(x)).doSomething3...

显然这效率不高,因为它迭代了数组 3 次。

我想知道是否有办法做这样的事情:

array.filterMany([
x => condition1(x).doSomething1...,
x => condition2(x).doSomething2...,
x => condition3(x).doSomething3...
])

这样数组就只迭代一次?

最佳答案

像这样怎么样?

const condition1 = x => x === 1;
const condition2 = x => x === 2;
const condition3 = x => x === 3;

[1, 2, 3].map(n => {
condition1(n) && console.log('foo');
condition2(n) && console.log('bar');
condition3(n) && console.log('baz');
})

关于javascript - 如何使用函数式编程过滤多个路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45801363/

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