Last active
February 21, 2023 06:11
-
-
Save Phryxia/54a7f7b3d82819106efac397860c708f to your computer and use it in GitHub Desktop.
TypeScript implementation of extracting every leaf values of given object into array
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
/** | |
* @param obj anything | |
* @param isSafe whether protect mutual dependency cycle case | |
* @returns every primitive properties of nested objects or arrays | |
*/ | |
function deepValues(obj: any, isSafe: boolean = false): any[] { | |
const out = [] as any[] | |
const dup = [] as (any[] | object)[] | |
function traverse(current: any) { | |
if (current == null || ['number', 'string', 'boolean', 'function'].includes(typeof current)) { | |
out.push(current) | |
return out | |
} | |
if (isSafe && dup.indexOf(current) > -1) { | |
return out | |
} | |
dup.push(current) | |
if (current instanceof Array) { | |
current.forEach(traverse) | |
return out | |
} | |
Object.values(current).forEach(traverse) | |
return out | |
} | |
return traverse(obj) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Note that when
isSafe === true
, time complexity blows up to O(n^2) where n is the number of non primitive things. There is no way to identify any arbitrary object nor array efficiently.