From 17add1f0fb6c911a91bc412d1b3aabe835abc2e6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pau=20Ferrer=20Oca=C3=B1a?= Date: Wed, 31 Aug 2022 13:36:00 +0200 Subject: [PATCH] MOBILE-4081 chore: Fix format tree with unsorted values --- src/core/services/utils/utils.ts | 24 ++++++++++++++++++------ 1 file changed, 18 insertions(+), 6 deletions(-) diff --git a/src/core/services/utils/utils.ts b/src/core/services/utils/utils.ts index 27e73a7da..d593de260 100644 --- a/src/core/services/utils/utils.ts +++ b/src/core/services/utils/utils.ts @@ -37,7 +37,7 @@ import { CoreColors } from '@singletons/colors'; import { CorePromisedValue } from '@classes/promised-value'; import { CorePlatform } from '@services/platform'; -type TreeNode = T & { children: TreeNode[] }; +export type TreeNode = T & { children: TreeNode[] }; /* * "Utils" service with helper functions. @@ -562,18 +562,30 @@ export class CoreUtilsProvider { const mapDepth = {}; const tree: TreeNode[] = []; + // Create a map first to avoid problems with not sorted. list.forEach((node: TreeNode, index): void => { const id = node[idFieldName]; - const parent = node[parentFieldName]; - node.children = []; - if (!id || !parent) { + if (id === undefined) { + this.logger.error(`Node with incorrect ${idFieldName}:${id} found on formatTree`); + } + + if (node.children === undefined) { + node.children = []; + } + map[id] = index; + }); + + list.forEach((node: TreeNode): void => { + const id = node[idFieldName]; + const parent = node[parentFieldName]; + + if (id === undefined || parent === undefined) { this.logger.error(`Node with incorrect ${idFieldName}:${id} or ${parentFieldName}:${parent} found on formatTree`); } // Use map to look-up the parents. - map[id] = index; - if (parent != rootParentId) { + if (parent !== rootParentId) { const parentNode = list[map[parent]] as TreeNode; if (parentNode) { if (mapDepth[parent] == maxDepth) {