Skip to content

Commit

Permalink
feat: Add a splitWhen utility
Browse files Browse the repository at this point in the history
jerelmiller committed Jun 11, 2020
1 parent a075eda commit 17d946b
Showing 2 changed files with 43 additions and 0 deletions.
28 changes: 28 additions & 0 deletions src/utils/__tests__/splitWhen.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import splitWhen from '../splitWhen';

test('splits the list into 2 chunks where the predicate is true', () => {
const list = [1, 2, 3, 4, 5];

const result = splitWhen(list, (num) => num === 3);

expect(result).toEqual([
[1, 2],
[3, 4, 5],
]);
});

test('returns empty list if there are no items', () => {
const list = [];

const result = splitWhen(list, () => true);

expect(result).toEqual([]);
});

test('handles list where no items satisfy the predicate', () => {
const list = [1, 2, 3];

const result = splitWhen(list, (num) => num === 10);

expect(result).toEqual([[1, 2, 3], []]);
});
15 changes: 15 additions & 0 deletions src/utils/splitWhen.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
const splitWhen = (list, predicate) => {
if (list.length === 0) {
return [];
}

const idx = list.findIndex((item) => predicate(item));

if (idx === -1) {
return [list, []];
}

return [list.slice(0, idx), list.slice(idx)];
};

export default splitWhen;

0 comments on commit 17d946b

Please sign in to comment.