Created
February 20, 2019 00:15
-
-
Save trusktr/5174095bb6f23f29c957d560d2e5c34e to your computer and use it in GitHub Desktop.
Obliterate an object
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
// recursively deletes all properties within an `object` or `function` | |
// TODO option to also handle non-enumerable but configurable descriptors | |
function obliterate(obj: object) { | |
const visited = new WeakSet | |
_obliterate(obj) | |
async function _obliterate(obj) { | |
if (!obj || !(typeof obj === 'object' || typeof obj === 'function')) return | |
// stop traversing if we already visited this object higher up | |
if (visited.has(obj)) return | |
visited.add(obj) | |
for (const [key, value] of Object.entries(obj)) { | |
try { | |
_obliterate(value) | |
} catch(e) { | |
if (e instanceof RangeError) { | |
await new Promise(resolve => setTimeout(resolve)) | |
_obliterate(value) | |
} | |
} | |
// NOTE unsuccessful deletions (f.e. for non-configurable properties) throw | |
// in strict mode | |
try { delete obj[key] } catch(e) {} | |
} | |
if (Array.isArray(obj)) | |
try { obj.length = 0 } catch(e) {} // some length props are readonly | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment