Last active
January 22, 2020 17:33
-
-
Save friendlyanon/b3887f284b4d1885ed3d32abf535d733 to your computer and use it in GitHub Desktop.
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
// guard against circular properties built in | |
function flatten(array) { | |
const { isArray } = Array; | |
if (!isArray(array)) { | |
return []; | |
} | |
const visited = new WeakSet; | |
const result = []; | |
const stack = [array]; | |
do { | |
const value = stack.pop(); | |
if (!isArray(value)) { | |
result.push(value); | |
continue; | |
} | |
if (visited.has(value)) { | |
continue; | |
} | |
visited.add(value); | |
for (const v of value) { | |
stack.push(v); | |
} | |
} while (stack.length); | |
return result.reverse(); | |
} | |
// without guard against circular properties | |
function flatten(array) { | |
const { isArray } = Array; | |
if (!isArray(array)) { | |
return []; | |
} | |
const result = []; | |
const stack = [array]; | |
do { | |
const value = stack.pop(); | |
if (!isArray(value)) { | |
result.push(value); | |
continue; | |
} | |
for (const v of value) { | |
stack.push(v); | |
} | |
} while (stack.length); | |
return result.reverse(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment