Skip to content

Instantly share code, notes, and snippets.

@Phryxia
Last active February 21, 2023 06:11
Show Gist options
  • Save Phryxia/54a7f7b3d82819106efac397860c708f to your computer and use it in GitHub Desktop.
Save Phryxia/54a7f7b3d82819106efac397860c708f to your computer and use it in GitHub Desktop.
TypeScript implementation of extracting every leaf values of given object into array
/**
* @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)
}
@Phryxia
Copy link
Author

Phryxia commented Feb 21, 2023

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment