forked from Chalarangelo/30-seconds-of-code
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
cc6dbcc
commit 1a53f7d
Showing
1 changed file
with
26 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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 | ||
``` |