From 17d946bfb0009f39b5e46bf5c46459cab5175805 Mon Sep 17 00:00:00 2001 From: Jerel Miller Date: Thu, 11 Jun 2020 12:06:22 -0700 Subject: [PATCH] feat: Add a splitWhen utility --- src/utils/__tests__/splitWhen.js | 28 ++++++++++++++++++++++++++++ src/utils/splitWhen.js | 15 +++++++++++++++ 2 files changed, 43 insertions(+) create mode 100644 src/utils/__tests__/splitWhen.js create mode 100644 src/utils/splitWhen.js 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;