UNPKG

@rimbu/proximity

Version:

Immutable ProximityMap implementation for TypeScript

58 lines 2.38 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.findNearestKeyMatch = findNearestKeyMatch; var tslib_1 = require("tslib"); /** * Given an Iterable of [key, value] entries, applies the distance function to * each key, finding the one closest to the input key, also returning its * associated value as well as the related distance; returns `undefined` * only when there are no successful match - that is, all the keys have +inf distance. * * Performs a full linear scan unless a distance equal to 0 is encountered, in which * case the function returns immediately; otherwise, the algorithm selects the * smallest *non-infinite* distance: if multiple keys happen to have such distance, * the selection order is not guaranteed. * * @param distanceFunction Returns the distance between two keys * @param key The key used as a reference to find the closest key * @param entries The [key, value] entries * @returns A `NearestKeyMatch` object if a closest key - * having a *finite distance* - exists; `undefined` otherwise */ function findNearestKeyMatch(distanceFunction, key, entries) { var e_1, _a; var bestEntry = undefined; var bestDistance = Number.POSITIVE_INFINITY; try { for (var entries_1 = tslib_1.__values(entries), entries_1_1 = entries_1.next(); !entries_1_1.done; entries_1_1 = entries_1.next()) { var _b = tslib_1.__read(entries_1_1.value, 2), currentKey = _b[0], currentValue = _b[1]; var currentDistance = distanceFunction(currentKey, key); if (!currentDistance) { return { key: currentKey, value: currentValue, distance: 0, }; } if (currentDistance < bestDistance) { bestEntry = [currentKey, currentValue]; bestDistance = currentDistance; } } } catch (e_1_1) { e_1 = { error: e_1_1 }; } finally { try { if (entries_1_1 && !entries_1_1.done && (_a = entries_1.return)) _a.call(entries_1); } finally { if (e_1) throw e_1.error; } } return bestEntry ? { key: bestEntry[0], value: bestEntry[1], distance: bestDistance, } : undefined; } //# sourceMappingURL=keyMatching.cjs.map