From a075eda079b2f837a125298466e77db858e369d4 Mon Sep 17 00:00:00 2001 From: Jerel Miller Date: Thu, 11 Jun 2020 11:52:21 -0700 Subject: [PATCH] feat: Add a splitUsing utility function --- src/utils/__tests__/splitUsing.js | 37 +++++++++++++++++++++++++++++++ src/utils/splitUsing.js | 20 +++++++++++++++++ 2 files changed, 57 insertions(+) create mode 100644 src/utils/__tests__/splitUsing.js create mode 100644 src/utils/splitUsing.js diff --git a/src/utils/__tests__/splitUsing.js b/src/utils/__tests__/splitUsing.js new file mode 100644 index 000000000..a5b864f61 --- /dev/null +++ b/src/utils/__tests__/splitUsing.js @@ -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]]); +}); diff --git a/src/utils/splitUsing.js b/src/utils/splitUsing.js new file mode 100644 index 000000000..49f13797c --- /dev/null +++ b/src/utils/splitUsing.js @@ -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;