2017-08-21 29 views
0

过滤到多条路径,我有以下伪代码:如何使用功能编程

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... 
]) 

+1

你能提供一个更清晰的例子吗? –

+0

使用数组减少。 – Neal

+2

难道你不能只用逻辑“和”'&&'? – clabe45

回答

0

您可以使用数组缩减功能。

例如:

const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; 
 
    
 
    const split = arr.reduce(([odd, even], current) => { 
 
     if (current % 2 === 0) { 
 
      even.push(current); 
 
     } else { 
 
      odd.push(current); 
 
     } 
 
    
 
     return [odd, even]; 
 
    }, [[], []]); 
 
    
 
    console.log('Odd/Even', split);

+0

谢谢。我只能在7分钟之内除外 – MotKohn

+0

乐意帮忙@MotKohn :-) – Neal

+1

如果有相同的价值可能会满足多种条件的机会,一定要把这个'if/else'变成一系列'if'! – shabs

1

怎么这样呢?

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'); 
 
})

+0

你期待'.map'函数做什么? – Neal

+0

@Neal只不过是一个'forEach'!也许这会更精确的语义。 – shabs

1

你可以采取的条件到一个数组中,并核对与Array#every

var conditions = [condition1, condition2, condition3], 
    filtered = array.filter(a => conditions.every(c => c(a)));