2017-04-22 69 views
0

我正在寻找一种方法来计算笛卡尔乘积中的EcmaScript 6如何计算乘积的迭代对象


例子:

product([["I", "They"], ["watch", "drink"], ["the sea", "the juice"]]) 

预期结果:

[["I", "watch", "the sea"], ["I", "watch", "the juice"], ["I", "drink", "the sea"], ["I", "drink", "the juice"], ["They", "watch", "the sea"], ["They", "watch", "the juice"], ["They", "drink", "the sea"], ["They", "drink", "the juice"]] 

例如:

product([[-1, -2], [10, 20]]) 

预期结果:

[[-1, 10], [-1, 20], [-2, 10], [-2, 20]] 
+0

什么是嵌套'for..of'循环,如果'arr2'不和的元素目的'arr1'? – guest271314

+0

笛卡尔产品! –

+0

认为,这比真正有用的东西更具挑战性! –

回答

2

的“假装JavaScript是哈斯克尔”版本:

const re = g => a => ({ 
    [Symbol.iterator]:() => g(a) 
}) 

const cons = x => re(function* (xs) { 
    yield x 
    yield* xs 
}) 

const map = f => re(function* (xs) { 
    for (const x of xs) 
    yield f(x) 
}) 

const ap = fs => re(function* (xs) { 
    for (const f of fs) 
    for (const x of xs) 
     yield f(x) 
}) 

const product = ([x, ...xs]) => 
    x ? ap(map(cons)(x))(product(xs)) : 
     [[]] 

使用方法如下(当然,不这样做,实际上):

for (const l of product([arr1, arr2, arr3])) 
    callback(...l) 

re使一个纯生成器可重用。

+0

谢谢!很有意思 ! –

1

基于Ryan的想法:

let flatten = arr => [].concat(...arr); 

function product([x, ...xs]) { 
    if(!x) return [[]]; 

    let next = product(xs); 

    return flatten(x.map(a => 
     next.map(b => [a, ...b]) 
    )); 
}