Created
July 31, 2019 10:55
-
-
Save AvocadoVenom/466cfaaea26e340ed9287ff5ab6a587e to your computer and use it in GitHub Desktop.
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
/** | |
* Unflatten an array of objects. | |
* | |
* @param arr An array of objects. | |
* @param keyFn Key property accessor function. | |
* @param parentFn Parent property accessor function. | |
* @example unflatten<FlatTreeNode>(x, i => i.id, i => i.parentId); | |
*/ | |
private unflatten<T>(arr: T[], keyFn: (item: T) => number, parentFn: (item: T) => number): T[] { | |
const tree = [], | |
map: Map<number, T> = new Map(arr.map(i => [keyFn(i), i])); | |
map.forEach(it => { | |
if (parentFn(it) === 0) { | |
tree.push(it); | |
} else { | |
let parent = map.get(parentFn(it)); | |
if (parent['children']) { | |
parent['children'].push(it); | |
} else { | |
parent['children'] = [it]; | |
} | |
} | |
}); | |
return tree; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment