Last active
January 29, 2020 11:15
-
-
Save mariuszklinger/330bbf5d7cd4fccc0f1b127c684c4a74 to your computer and use it in GitHub Desktop.
custom infinite flat() in js
This file contains hidden or 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
| const example1 = [[1, 1, 1, [1.4, 1.6]], 666, [2, 3, [[4], [5, 6]]]]; | |
| function flat(arr) { | |
| const stack = arr; | |
| const result = []; | |
| while (stack.length) { | |
| const current = stack.shift(); | |
| const isCurrentArray = Array.isArray(current); | |
| if (isCurrentArray) { | |
| stack.unshift(...current); | |
| continue; | |
| } | |
| result.push(current); | |
| } | |
| return result; | |
| } | |
| console.assert(`${flat(example1)}`, '1,1,1,1.4,1.6,666,2,3,4,5,6'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment