Skip to content

Instantly share code, notes, and snippets.

@skiano
Created February 9, 2022 05:36
Show Gist options
  • Save skiano/766d92911ad3861366993335a1bbc9ea to your computer and use it in GitHub Desktop.
Save skiano/766d92911ad3861366993335a1bbc9ea to your computer and use it in GitHub Desktop.
gen traverse but skip dulicates!
function* each(arr) {
let i;
for (i = 0; i < arr.length; i++) yield arr[i];
}
export function* traverse (arr) {
let queue = [each(arr)];
let seen = new WeakSet();
while (queue.length) {
const { value, done } = queue[0].next();
if (Array.isArray(value)) {
let skip;
if (value.__once__) {
if (seen.has(value)) skip = true;
else seen.add(value);
}
if (!skip) queue.unshift(each(value))
} else {
if (value) yield value;
if (done) {
queue.shift();
}
}
}
}
const unique = ['a', 'b', ['c', 'd']];
unique.__once__ = true;
const it = traverse([
1,
unique,
2,
[3, 4, [5], [6, 7], unique],
8,
[[]],
unique,
9
])
for (let v of it) {
console.log(v);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment