diff --git a/src/utils/__tests__/splitWhen.js b/src/utils/__tests__/splitWhen.js new file mode 100644 index 000000000..ac3c27088 --- /dev/null +++ b/src/utils/__tests__/splitWhen.js @@ -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], []]); +}); diff --git a/src/utils/splitWhen.js b/src/utils/splitWhen.js new file mode 100644 index 000000000..5f9febb60 --- /dev/null +++ b/src/utils/splitWhen.js @@ -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;