Skip to content

Commit 8865b82

Browse files
✨ feat(enumerate): First draft.
1 parent 41c46e6 commit 8865b82

File tree

4 files changed

+49
-1
lines changed

4 files changed

+49
-1
lines changed

src/_enumerate.js

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
import {list, map} from '@aureooms/js-itertools';
2+
3+
export default function* _enumerate(elements, n = elements.length) {
4+
if (n === 0) yield [];
5+
else {
6+
const last = elements[n - 1];
7+
for (const partition of _enumerate(elements, n - 1)) {
8+
yield partition.concat([[last]]);
9+
for (const part of partition) {
10+
yield list(map((p) => (p === part ? p.concat([last]) : p), partition));
11+
}
12+
}
13+
}
14+
}

src/enumerate.js

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
import {list} from '@aureooms/js-itertools';
2+
3+
import _enumerate from './_enumerate';
4+
5+
export default function enumerate(elements) {
6+
return _enumerate(list(elements));
7+
}

src/index.js

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,16 @@
1+
import _enumerate from './_enumerate';
12
import count from './count';
3+
import enumerate from './enumerate';
24
import isPartition from './isPartition';
35
import sequence from './sequence';
46

57
/* eslint import/no-anonymous-default-export: [2, {"allowObject": true}] */
68
export default {
9+
_enumerate,
710
count,
11+
enumerate,
812
isPartition,
913
sequence,
1014
};
1115

12-
export {count, isPartition, sequence};
16+
export {_enumerate, count, enumerate, isPartition, sequence};

test/src/enumerate.js

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
import test from 'ava';
2+
3+
import {range, list, map} from '@aureooms/js-itertools';
4+
import {enumerate} from '../../src';
5+
6+
const macro = (t, n, expected) => {
7+
const elements = range(n);
8+
t.deepEqual(list(map(list, enumerate(elements))), expected);
9+
};
10+
11+
macro.title = (title, n, expected) =>
12+
`enumerate(range(${n})) = ${JSON.stringify(expected)}`;
13+
14+
test(macro, 0, [[]]);
15+
test(macro, 1, [[[0]]]);
16+
test(macro, 2, [[[0], [1]], [[0, 1]]]);
17+
test(macro, 3, [
18+
[[0], [1], [2]],
19+
[[0, 2], [1]],
20+
[[0], [1, 2]],
21+
[[0, 1], [2]],
22+
[[0, 1, 2]],
23+
]);

0 commit comments

Comments
 (0)