Skip to content

Commit

Permalink
feat: Add a splitUsing utility function
Browse files Browse the repository at this point in the history
  • Loading branch information
jerelmiller committed Jun 11, 2020
1 parent 11acfca commit a075eda
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 0 deletions.
37 changes: 37 additions & 0 deletions src/utils/__tests__/splitUsing.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import splitUsing from '../splitUsing';

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

const result = splitUsing(list, (num) => num === 2);

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

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

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

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

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

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

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

test('handles list where all items satisfy the predicate', () => {
const list = [0, 0, 0, 0];

const result = splitUsing(list, (num) => num === 0);

expect(result).toEqual([[0], [0], [0], [0]]);
});
20 changes: 20 additions & 0 deletions src/utils/splitUsing.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
const splitUsing = (list, predicate) => {
const { groups, items } = list.reduce(
({ groups, items }, item) => {
if (predicate(item)) {
return { groups: groups.concat([items.concat(item)]), items: [] };
}

return { groups: groups, items: items.concat(item) };
},
{ groups: [], items: [] }
);

if (items.length > 1) {
return [...groups, items];
}

return groups;
};

export default splitUsing;

0 comments on commit a075eda

Please sign in to comment.