Skip to content

Commit

Permalink
feat: Introduce combinations in fp
Browse files Browse the repository at this point in the history
  • Loading branch information
Iku-turso committed Jan 15, 2023
1 parent 09ee015 commit 88f0617
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 0 deletions.
9 changes: 9 additions & 0 deletions packages/fp/src/combinations/combinations.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { reduce } from 'lodash/fp';

const appendTo = values => value => [...values, value];

export default reduce(
(accumulated, current) =>
accumulated.flatMap(values => current.map(appendTo(values))),
[[]],
);
50 changes: 50 additions & 0 deletions packages/fp/src/combinations/combinations.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import combinations from './combinations';

describe('combinations', () => {
it('given arrays of same size, returns all combinations', () => {
const actual = combinations([
[1, 2],
[3, 4],
[5, 6],
]);

const expected = [
[1, 3, 5],
[1, 3, 6],
[1, 4, 5],
[1, 4, 6],
[2, 3, 5],
[2, 3, 6],
[2, 4, 5],
[2, 4, 6],
];

expect(actual).toEqual(expected);
});

it('given arrays of different size, returns all combinations', () => {
const actual = combinations([
[1, 2],
[3, 4, 5],
]);

const expected = [
[1, 3],
[1, 4],
[1, 5],
[2, 3],
[2, 4],
[2, 5],
];

expect(actual).toEqual(expected);
});

it('given one of the arrays is empty, returns no combinations', () => {
const actual = combinations([[1, 2], [], [3, 4, 5]]);

const expected = [];

expect(actual).toEqual(expected);
});
});

0 comments on commit 88f0617

Please sign in to comment.