All files / app/codeCharta/ui/ribbonBar/searchPanel/mapTreeView/mapTreeViewNodeSelector sortNode.ts

96.77% Statements 30/31
87.5% Branches 7/8
100% Functions 6/6
96.15% Lines 25/26

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 494x       4x 18x 4x   4x 18x 18x     4x 18x 18x   18x 29x 13x   16x       18x 18x   18x       4x 18x       18x 29x 13x       18x 18x   18x    
import { CodeMapNode, NodeType, SortingOption } from "../../../../../codeCharta.model"
 
type CompareFunction = (a: CodeMapNode, b: CodeMapNode) => number
 
const nameCollator = new Intl.Collator(undefined, { numeric: true, sensitivity: "base" })
const sortByName: CompareFunction = (a, b) => nameCollator.compare(a.name, b.name)
const sortByUnary: CompareFunction = (a, b) => a.attributes.unary - b.attributes.unary
 
const getCompareFunction = (sortingOrder: SortingOption, sortingOrderAscending: boolean) => {
    const compareFunction = sortingOrder === SortingOption.NUMBER_OF_FILES ? sortByUnary : sortByName
    return sortingOrderAscending ? compareFunction : (a: CodeMapNode, b: CodeMapNode) => -1 * compareFunction(a, b)
}
 
const groupAndSortNodeByFilesAndFolders = (compareFunction: CompareFunction, node: CodeMapNode) => {
    const folders: CodeMapNode[] = []
    const files: CodeMapNode[] = []
 
    for (const child of node.children) {
        if (child.type === NodeType.FOLDER) {
            folders.push(child)
        } else {
            files.push(child)
        }
    }
 
    folders.sort(compareFunction)
    files.sort(compareFunction)
 
    return [...folders, ...files]
}
 
/** sort given node inplace */
export const sortNode = (node: CodeMapNode, sortingOrder: SortingOption, sortingOrderAscending: boolean) => {
    Iif (!node) {
        return
    }
 
    for (let index = 0; index < node.children.length; index++) {
        if (node.children[index].type === NodeType.FOLDER) {
            node.children[index] = sortNode(node.children[index], sortingOrder, sortingOrderAscending)
        }
    }
 
    const compareFunction = getCompareFunction(sortingOrder, sortingOrderAscending)
    node.children = groupAndSortNodeByFilesAndFolders(compareFunction, node)
 
    return node
}