Skip to content

Instantly share code, notes, and snippets.

@tzkmx
Created November 9, 2020 05:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tzkmx/c2f62941d16c1c5615b7e34ef96c5bee to your computer and use it in GitHub Desktop.
Save tzkmx/c2f62941d16c1c5615b7e34ef96c5bee to your computer and use it in GitHub Desktop.
WeakSet as potential call stack overflow prevention?
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakSet
// Execute a callback on everything stored inside an object
function execRecursively(fn, subject, _refs = null){
if(!_refs)
_refs = new WeakSet();
// Avoid infinite recursion
if(_refs.has(subject))
return;
fn(subject);
if("object" === typeof subject){
_refs.add(subject);
for(let key in subject)
execRecursively(fn, subject[key], _refs);
}
}
const foo = {
foo: "Foo",
bar: {
bar: "Bar"
}
};
foo.bar.baz = foo; // Circular reference!
execRecursively(obj => console.log(obj), foo);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment