From 1a53f7de0b170658606eb7d26ab020e41e6a0259 Mon Sep 17 00:00:00 2001 From: Chalarangelo Date: Wed, 9 Mar 2022 16:56:01 +0200 Subject: [PATCH] Add flatIterator --- snippets/flatIterator.md | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 snippets/flatIterator.md diff --git a/snippets/flatIterator.md b/snippets/flatIterator.md new file mode 100644 index 00000000000..f94f238cdeb --- /dev/null +++ b/snippets/flatIterator.md @@ -0,0 +1,26 @@ +--- +title: Flat iterator +tags: array,iterator,generator +expertise: advanced +firstSeen: 2022-03-09T05:00:00-04:00 +--- + +Creates a generator that iterates over an iterable, flattening nested iterables. + +- Use recursion. +- Use a `for...of` loop to iterate over the values of the given iterable. +- Use `Symbol.iterator` to check if each value is an iterable. If it is, use the `yield*` expression to recursively delegate to the same generator function. Otherwise, `yield` the current value. + +```js +const flatIterator = function* (itr) { + for (let item of itr) { + if (item[Symbol.iterator]) yield* flatIterator(item); + else yield item; + } +}; +``` + +```js +const arr = [1, 2, [3, 4], [5, [6, [7], 8]], 9, new Set([10, 11])]; +[...flatIterator(arr)]; // 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 +```