Skip to content

Commit

Permalink
Fix generators
Browse files Browse the repository at this point in the history
  • Loading branch information
ehmicky committed May 28, 2019
1 parent 1877271 commit acd36ea
Show file tree
Hide file tree
Showing 4 changed files with 40 additions and 5 deletions.
21 changes: 16 additions & 5 deletions src/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,10 @@ const fastCartesian = function(...iterables) {

iterables.forEach(validateIterable)

const arrays = iterables.map(arrify)

const result = []
iterate(iterables, result, [], 0)
iterate(arrays, result, [], 0)
return result
}

Expand All @@ -23,19 +25,28 @@ const validateIterable = function(iterable) {
}
}

// Some iterables are stateful, e.g. generators. We need to iterate them first.
const arrify = function(iterable) {
if (Array.isArray(iterable)) {
return iterable
}

return [...iterable]
}

// We use imperative code as it faster than functional code because it does not
// create extra arrays. We try re-use and mutate arrays as much as possible.
// We need to make sure callers parameters are not mutated though.
/* eslint-disable max-params, fp/no-loops, fp/no-mutating-methods */
const iterate = function(iterables, result, values, index) {
if (index === iterables.length) {
const iterate = function(arrays, result, values, index) {
if (index === arrays.length) {
result.push(values.slice())
return
}

for (const value of iterables[index]) {
for (const value of arrays[index]) {
values.push(value)
iterate(iterables, result, values, index + 1)
iterate(arrays, result, values, index + 1)
values.pop()
}
}
Expand Down
1 change: 1 addition & 0 deletions test/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ const generator = function*() {
[new Map([[{}, 0], [{}, 1]])],
[new Set([0, 1])],
[generator()],
[[0, 1], generator()],
].forEach(args => {
const title = prettyFormat(args, { min: true })
test(title, t => {
Expand Down
23 changes: 23 additions & 0 deletions test/snapshots/main.js.md
Original file line number Diff line number Diff line change
Expand Up @@ -231,3 +231,26 @@ Generated by [AVA](https://ava.li).
1,
],
]

## [[0, 1], {}]

> Snapshot 1
[
[
0,
0,
],
[
0,
1,
],
[
1,
0,
],
[
1,
1,
],
]
Binary file modified test/snapshots/main.js.snap
Binary file not shown.

0 comments on commit acd36ea

Please sign in to comment.