@darkobits/valida
Version:
Type-aware object validator.
67 lines (50 loc) • 2.49 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = suggestKey;
var _fastestLevenshtein = require("fastest-levenshtein");
var R = _interopRequireWildcard(require("ramda"));
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
function levenshteinDistanceMatrix(stringsA, stringsB, maxDistance = 2) {
if (R.difference(stringsA, stringsB).length === 0) {
return;
}
const results = [];
for (const stringA of stringsA) {
for (const stringB of stringsB) {
if (stringA === stringB) {
break;
}
const distance = (0, _fastestLevenshtein.distance)(stringA, stringB);
if (distance <= maxDistance) {
results.push({
distance,
stringA,
stringB
});
}
}
}
const sortedResults = R.sortBy(R.prop('distance'), results);
const [closestResult] = sortedResults;
return closestResult;
}
function suggestKey(validKeys, testKeys) {
const missingKeys = R.difference(validKeys, testKeys);
if (missingKeys.length === 0) {
return true;
}
const extraneousKeys = R.difference(testKeys, validKeys);
const match = levenshteinDistanceMatrix(missingKeys, extraneousKeys);
if (!match) {
return true;
}
return {
missingKey: match.stringA,
closestExtraneousKey: match.stringB
};
}
module.exports = exports.default;
//# sourceMappingURL=suggest-key.js.map