Skip to content

Instantly share code, notes, and snippets.

@friendlyanon
Last active January 22, 2020 17:33
Show Gist options
  • Save friendlyanon/b3887f284b4d1885ed3d32abf535d733 to your computer and use it in GitHub Desktop.
Save friendlyanon/b3887f284b4d1885ed3d32abf535d733 to your computer and use it in GitHub Desktop.
// 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