All files / app/codeCharta/ui/copyToClipboardButton/util getFilenamesWithHighestMetrics.ts

100% Statements 27/27
100% Branches 17/17
100% Functions 8/8
100% Lines 24/24

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 49 50 51 52 53 54 55 56 57 58 59 60 61 624x 4x       4x       4x       4x   4x 53x 45x       4x       53x               45x 89x 89x   89x 9x   80x 80x 80x           80x 278x   80x 28x   52x         220x    
import { hierarchy } from "d3-hierarchy"
import { AttributeDescriptors, CodeMapNode, NodeType } from "../../../codeCharta.model"
 
export type FileToValue = { filePath: string; value: number }
 
const MAX_ENTRIES = 10
 
type ReducedCodeMapNode = Pick<CodeMapNode, "type" | "attributes" | "path"> & { children?: ReducedCodeMapNode[] }
 
export function getFilenamesWithHighestMetrics(
    node: ReducedCodeMapNode,
    attributeDescriptors: AttributeDescriptors
): Map<string, FileToValue[]> {
    const aggregatedMetrics = new Map<string, FileToValue[]>()
 
    for (const { data } of hierarchy(node)) {
        if (isFileNode(data)) {
            updateMetricsForNode(data, attributeDescriptors, aggregatedMetrics)
        }
    }
 
    return aggregatedMetrics
}
 
function isFileNode(node: ReducedCodeMapNode): boolean {
    return node.type === NodeType.FILE && node.attributes !== undefined
}
 
function updateMetricsForNode(
    node: ReducedCodeMapNode,
    attributeDescriptors: AttributeDescriptors,
    aggregatedMetrics: Map<string, FileToValue[]>
) {
    for (const [attribute, value] of Object.entries(node.attributes)) {
        const direction = attributeDescriptors?.[attribute]?.direction
        const metricEntry = { filePath: node.path, value }
 
        if (!aggregatedMetrics.has(attribute)) {
            aggregatedMetrics.set(attribute, [metricEntry])
        } else {
            const existingMetrics = aggregatedMetrics.get(attribute)
            insertMetricInOrder(existingMetrics, metricEntry, direction)
            aggregatedMetrics.set(attribute, existingMetrics.slice(0, MAX_ENTRIES))
        }
    }
}
 
function insertMetricInOrder(metrics: FileToValue[], newMetric: FileToValue, direction: number) {
    const comparisonFunction = getComparisonFunction(direction)
    const insertionIndex = metrics.findIndex(metric => comparisonFunction(newMetric, metric) < 0)
 
    if (insertionIndex === -1) {
        metrics.push(newMetric)
    } else {
        metrics.splice(insertionIndex, 0, newMetric)
    }
}
 
function getComparisonFunction(direction: number): (a: FileToValue, b: FileToValue) => number {
    return direction === 1 ? (a, b) => a.value - b.value : (a, b) => b.value - a.value
}