UNPKG

closest-property

Version:

When given an object and a string, will return the value corresponding to the key that is the closest (according to the levenshtein distance, where case is ignored) to the given string.

58 lines (57 loc) 1.59 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); /** * Calculates the number of edits to get from input1 to input2 where an edit is * one of: * * 1. Add a character; * 2. Delete a character; or, * 3. Replace a character. * * @param input1 * @param input2 */ exports.editDistance = function (input1, input2) { if (input1 === void 0) { input1 = ''; } if (input2 === void 0) { input2 = ''; } var s1 = input1.toLowerCase(); var s2 = input2.toLowerCase(); var dp = []; for (var i = 0; i <= s1.length; i++) dp.push(i); for (var j = 0; j < s2.length; j++) { var remember = dp[0]; dp[0] = j + 1; for (var i = 0; i < s1.length; i++) { var next = s1[i] === s2[j] ? remember : 1 + Math.min(dp[i], // add a character dp[i + 1], // delete a charcter remember); remember = dp[i + 1]; dp[i + 1] = next; } } return dp[dp.length - 1]; }; /** * When given an object and a target string, returns the [first] value with the * key that is the least distance from the target string. * * @param obj * @param target */ function closest(obj, target) { var minDistance = Infinity; var minValue; Object.keys(obj).forEach(function (key) { var dist = exports.editDistance(key, target); if (dist < minDistance) { minDistance = dist; minValue = obj[key]; } }); return minValue; } exports.default = closest;