Skip to content

Instantly share code, notes, and snippets.

@AvocadoVenom
Created July 31, 2019 10:55
Show Gist options
  • Save AvocadoVenom/466cfaaea26e340ed9287ff5ab6a587e to your computer and use it in GitHub Desktop.
Save AvocadoVenom/466cfaaea26e340ed9287ff5ab6a587e to your computer and use it in GitHub Desktop.
/**
* 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