From e0e23aaae4dd0297db0c341f39b7e0dacd3bafe7 Mon Sep 17 00:00:00 2001 From: Chalarangelo Date: Tue, 16 Mar 2021 22:50:40 +0200 Subject: [PATCH] Add chunkify --- snippets/chunkify.md | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 snippets/chunkify.md diff --git a/snippets/chunkify.md b/snippets/chunkify.md new file mode 100644 index 000000000..00d6ac04c --- /dev/null +++ b/snippets/chunkify.md @@ -0,0 +1,29 @@ +--- +title: chunkify +tags: function,generator,array,advanced +--- + +Chunks an iterable into smaller arrays of a specified size. + +- Use a `for...of` loop over the given iterable, using `Array.prototype.push()` to add each new value to the current `chunk`. +- Use `Array.prototype.length` to check if the current `chunk` is of the desired `size` and `yield` the value if it is. +- Finally, use `Array.prototype.length` to check the final `chunk` and `yield` it if it's non-empty. + +```js +const chunkify = function* (itr, size) { + let chunk = []; + for (const v of itr) { + chunk.push(v); + if (chunk.length === size) { + yield chunk; + chunk = []; + } + } + if (chunk.length) yield chunk; +}; +``` + +```js +const x = new Set([1, 2, 1, 3, 4, 1, 2, 5]); +[...chunkify(x, 2)]; // [[1, 2], [3, 4], [5]] +```