Skip to content

Instantly share code, notes, and snippets.

@trusktr
Created February 20, 2019 00:15
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save trusktr/5174095bb6f23f29c957d560d2e5c34e to your computer and use it in GitHub Desktop.
Save trusktr/5174095bb6f23f29c957d560d2e5c34e to your computer and use it in GitHub Desktop.
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