-
Notifications
You must be signed in to change notification settings - Fork 114
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: Add a splitUsing utility function
- Loading branch information
1 parent
11acfca
commit a075eda
Showing
2 changed files
with
57 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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]]); | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |