UNPKG

@appium/base-driver

Version:

Base driver class for Appium drivers

61 lines 2.83 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.LEVENSHTEIN_SUGGESTION_MAX_EDIT_DISTANCE = void 0; exports.rankLevenshteinCandidates = rankLevenshteinCandidates; exports.sortByLevenshteinDistance = sortByLevenshteinDistance; exports.getLevenshteinSuggestion = getLevenshteinSuggestion; const fastest_levenshtein_1 = require("fastest-levenshtein"); const lodash_1 = __importDefault(require("lodash")); /** * Inclusive maximum Levenshtein edit distance for offering a "did you mean" hint. * Matches with distance greater than this value are treated as unrelated. */ exports.LEVENSHTEIN_SUGGESTION_MAX_EDIT_DISTANCE = 2; /** * Sorts candidates by Levenshtein distance from `target` and optionally picks a suggestion * when the closest match is within `maxEditDistance` edits (single pass over candidates). */ function rankLevenshteinCandidates(target, candidates, maxEditDistance = exports.LEVENSHTEIN_SUGGESTION_MAX_EDIT_DISTANCE) { if (!candidates.length) { return { sorted: [], suggestion: undefined }; } const matchesMap = candidates .map((name) => [(0, fastest_levenshtein_1.distance)(target, name), name]) .reduce((acc, [dist, name]) => { const key = String(dist); if (key in acc) { acc[key].push(name); } else { acc[key] = [name]; } return acc; }, {}); const sortedDistanceKeys = lodash_1.default.keys(matchesMap).sort((a, b) => parseInt(a, 10) - parseInt(b, 10)); const sorted = lodash_1.default.flatten(sortedDistanceKeys.map((k) => (matchesMap[k] ?? []).sort())); const best = sorted[0]; const firstDistanceKey = sortedDistanceKeys[0]; const minDist = firstDistanceKey !== undefined ? parseInt(firstDistanceKey, 10) : NaN; const suggestion = maxEditDistance >= 0 && best !== undefined && !Number.isNaN(minDist) && minDist <= maxEditDistance ? best : undefined; return { sorted, suggestion }; } /** * Sorts strings by ascending Levenshtein distance from `target`. * Strings with the same distance are sorted alphabetically. */ function sortByLevenshteinDistance(target, candidates) { return rankLevenshteinCandidates(target, candidates, Number.POSITIVE_INFINITY).sorted; } /** * Returns the closest string in `candidates` by Levenshtein distance only if that * distance is at most `maxEditDistance` (inclusive). */ function getLevenshteinSuggestion(target, candidates, maxEditDistance = exports.LEVENSHTEIN_SUGGESTION_MAX_EDIT_DISTANCE) { return rankLevenshteinCandidates(target, candidates, maxEditDistance).suggestion; } //# sourceMappingURL=levenshtein-match.js.map