Skip to content

Instantly share code, notes, and snippets.

@15joeybloom
Created December 8, 2020 03:01
Show Gist options
  • Save 15joeybloom/46d757801c32c9fea33b6ccc59293ac9 to your computer and use it in GitHub Desktop.
Save 15joeybloom/46d757801c32c9fea33b6ccc59293ac9 to your computer and use it in GitHub Desktop.
A typescript function to truncate a potentially circular structure to a finite depth
// Takes a structure with possible circular references, e.g.
// functions.https.CallableContext, and truncates it to finite depth.
function finiteDepth(x: any, depth: bigint): any {
if (depth <= 0) {
return "Truncated by finiteDepth"
} else if (x instanceof Array) {
return x.map(e => finiteDepth(e, depth - 1n))
} else if (typeof x === 'object' && x !== null) {
return Object.fromEntries(
Object.entries(x).map(
([k, v]) => [k, finiteDepth(v, depth - 1n)]))
} else {
return x
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment