@rushstack/lookup-by-path
Version:
Strongly typed trie data structure for path and URL-like strings.
76 lines • 2.82 kB
JavaScript
;
// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.
// See LICENSE in the project root for license information.
Object.defineProperty(exports, "__esModule", { value: true });
exports.getFirstDifferenceInCommonNodes = getFirstDifferenceInCommonNodes;
/**
* Recursively compares two path tries to find the first shared node with a different value.
*
* @param options - The options for the comparison
* @returns The path to the first differing node, or undefined if they are identical
*
* @remarks
* Ignores any nodes that are not shared between the two tries.
*
* @beta
*/
function getFirstDifferenceInCommonNodes(options) {
const { first, second, prefix = '', delimiter = '/', equals = defaultEquals } = options;
return getFirstDifferenceInCommonNodesInternal({
first,
second,
prefix,
delimiter,
equals
});
}
/**
* Recursively compares two path tries to find the first shared node with a different value.
*
* @param options - The options for the comparison
* @returns The path to the first differing node, or undefined if they are identical
*
* @remarks
* Ignores any nodes that are not shared between the two tries.
* Separated out to avoid redundant parameter defaulting in the recursive calls.
*/
function getFirstDifferenceInCommonNodesInternal(options) {
const { first, second, prefix, delimiter, equals } = options;
const firstItem = first.value;
const secondItem = second.value;
if (firstItem !== undefined && secondItem !== undefined && !equals(firstItem, secondItem)) {
// If this value was present in both tries with different values, return the prefix for this node.
return prefix;
}
const { children: firstChildren } = first;
const { children: secondChildren } = second;
if (firstChildren && secondChildren) {
for (const [key, firstChild] of firstChildren) {
const secondChild = secondChildren.get(key);
if (!secondChild) {
continue;
}
const result = getFirstDifferenceInCommonNodesInternal({
first: firstChild,
second: secondChild,
prefix: key,
delimiter,
equals
});
if (result !== undefined) {
return prefix ? `${prefix}${delimiter}${result}` : result;
}
}
}
return;
}
/**
* Default equality function for comparing two items, using strict equality.
* @param a - The first item to compare
* @param b - The second item to compare
* @returns True if the items are reference equal, false otherwise
*/
function defaultEquals(a, b) {
return a === b;
}
//# sourceMappingURL=getFirstDifferenceInCommonNodes.js.map