From 1f212c00e1c5d23b4c733564aacfb0ccf127c412 Mon Sep 17 00:00:00 2001 From: Iku-turso Date: Sun, 15 Jan 2023 13:30:45 +0200 Subject: [PATCH] feat: Introduce movingWindow in fp --- packages/fp/src/movingWindow/movingWindow.js | 8 ++++++++ packages/fp/src/movingWindow/movingWindow.test.js | 13 +++++++++++++ 2 files changed, 21 insertions(+) create mode 100644 packages/fp/src/movingWindow/movingWindow.js create mode 100644 packages/fp/src/movingWindow/movingWindow.test.js diff --git a/packages/fp/src/movingWindow/movingWindow.js b/packages/fp/src/movingWindow/movingWindow.js new file mode 100644 index 00000000..3b974d00 --- /dev/null +++ b/packages/fp/src/movingWindow/movingWindow.js @@ -0,0 +1,8 @@ +export default windowSize => things => + things.reduce( + (accumulated, currentThing, index, allThings) => + index > allThings.length - windowSize + ? accumulated + : [...accumulated, allThings.slice(index, index + windowSize)], + [], + ); diff --git a/packages/fp/src/movingWindow/movingWindow.test.js b/packages/fp/src/movingWindow/movingWindow.test.js new file mode 100644 index 00000000..61d8f305 --- /dev/null +++ b/packages/fp/src/movingWindow/movingWindow.test.js @@ -0,0 +1,13 @@ +import movingWindow from './movingWindow'; + +describe('movingWindow', () => { + it('iterates an n-width window through an array', () => { + const actual = movingWindow(3)([1, 2, 3, 4, 5]); + + expect(actual).toEqual([ + [1, 2, 3], + [2, 3, 4], + [3, 4, 5], + ]); + }); +});