Created
November 9, 2020 05:41
-
-
Save tzkmx/c2f62941d16c1c5615b7e34ef96c5bee to your computer and use it in GitHub Desktop.
WeakSet as potential call stack overflow prevention?
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
// 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