Created
December 8, 2020 03:01
-
-
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
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
// 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