Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Obliterate an object
// 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