From db6dc948996df449363f17c83f1c4c848c084b3a Mon Sep 17 00:00:00 2001 From: Chalarangelo Date: Fri, 18 Jun 2021 21:56:23 +0300 Subject: [PATCH] Add mapConsecutive --- snippets/mapConsecutive.md | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 snippets/mapConsecutive.md diff --git a/snippets/mapConsecutive.md b/snippets/mapConsecutive.md new file mode 100644 index 000000000..d3006c03e --- /dev/null +++ b/snippets/mapConsecutive.md @@ -0,0 +1,20 @@ +--- +title: mapConsecutive +tags: array,intermediate +firstSeen: 2021-08-08T05:00:00-04:00 +--- + +Maps each block of `n` consencutive elements using the given function, `fn`. + +- Use `Array.prototype.slice()` to get `arr` with `n` elements removed from the left. +- Use `Array.prototype.map()` and `Array.prototype.slice()` to apply `fn` to each block of `n` consecutive elements in `arr`. + +```js +const mapConsecutive = (arr, n, fn) => + arr.slice(n - 1).map((v, i) => fn(arr.slice(i, i + n))); +``` + +```js +mapConsecutive([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 3, x => x.join('-')); +// ['1-2-3', '2-3-4', '3-4-5', '4-5-6', '5-6-7', '6-7-8', '7-8-9', '8-9-10']; +```