0

I am looking for a way to calculate cartesian product in EcmaScript 6


Example :

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

Expected result :

[["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"]]

Example :

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

Expected result :

[[-1, 10], [-1, 20], [-2, 10], [-2, 20]]
5
  • What is purpose of nested for..of loops if arr2 is not and element of arr1? Commented Apr 22, 2017 at 4:08
  • Cartesian product ! Commented Apr 22, 2017 at 4:14
  • Thought, it's more a challenge, than something really useful ! Commented Apr 22, 2017 at 4:20
  • Given example javascript at Question, and none of nested loops appearing to depend on property or value from preceding for..loop, not certain what expected result is? Commented Apr 22, 2017 at 4:26
  • 2
    The goal is to get a cartesian product = all the possibilities when you combine the arrays Commented Apr 22, 2017 at 4:30

2 Answers 2

2

The “pretend JavaScript is Haskell” version:

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)) :
      [[]]

Use as follows (well, don’t, actually):

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

re makes a pure generator reusable.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you ! Very interesting !
1

Based on Ryan's idea :

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.