cockatoo.js
Version:
Fuzzy search library based based on Damerau Levenshtein distance algorithm for Node.js
329 lines (328 loc) • 16.5 kB
JavaScript
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
Object.defineProperty(exports, "__esModule", { value: true });
var utils_1 = require("./utils");
var damerauLevenshtein_1 = require("./damerauLevenshtein");
var match_1 = require("./match");
var tokenMatch_1 = require("./tokenMatch");
var Cockatoo = /** @class */ (function () {
/**
* Create a Cockatoo.js instance
*/
function Cockatoo(elementsList, options, maxCacheElements) {
if (maxCacheElements === void 0) { maxCacheElements = 100; }
var _this = this;
this.damLev = new damerauLevenshtein_1.DamerauLevenshtein();
this.cache = {};
this.elementsList = elementsList;
this.options = options;
this.maxCacheElements = maxCacheElements;
this.originalValuesList = this.generateValuesList(elementsList, this.options);
if (this.options.tokenize) {
this.originalTokensList = this.generateTokensList(this.originalValuesList);
}
this.searchableValuesList = this.originalValuesList
.map(function (values) {
return values.map(function (value) { return utils_1.applySensitiveness(value, _this.options); });
});
if (this.options.tokenize) {
this.searchableTokensList = this.generateTokensList(this.searchableValuesList);
}
}
Cockatoo.prototype.search = function (searchText, filter) {
return __awaiter(this, void 0, void 0, function () {
var originalSearchText, searchTextTokens, originalSearchTextTokens, matches, promises, searchableIndexes, i, cacheKeysOrdered;
var _this = this;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
// If search text is empty, return []
if (searchText.length === 0) {
return [2 /*return*/, []];
}
// If there is result in cache, update date and return it
if (this.cache[searchText]) {
this.cache[searchText].date = new Date();
if (filter !== undefined) {
return [2 /*return*/, this.cache[searchText].results.filter(function (match) {
return filter(match.item);
})];
}
else {
return [2 /*return*/, this.cache[searchText].results];
}
}
originalSearchText = searchText;
searchText = utils_1.applySensitiveness(searchText, this.options);
searchTextTokens = this.getTokensFromText(searchText);
originalSearchTextTokens = this.getTokensFromText(originalSearchText);
matches = [];
promises = [];
if (filter !== undefined) {
searchableIndexes = this.elementsList
.map(function (value, index) {
return { index: index, value: value };
})
.filter(function (_a) {
var value = _a.value;
return filter(value);
})
.map(function (_a) {
var index = _a.index;
return index;
});
}
else {
searchableIndexes = this.elementsList
.map(function (value, index) {
return index;
});
}
for (i = 0; i < searchableIndexes.length; i++) {
promises.push(this.getMatch(searchText, searchTextTokens, originalSearchTextTokens, searchableIndexes[i])
.then(function (match) {
if (match !== undefined) {
matches.push(match);
}
}));
}
return [4 /*yield*/, Promise.all(promises)];
case 1:
_a.sent();
if (this.options.sorted) {
matches = utils_1.orderMatches(matches);
}
// If cache overflow, delete oldest entry
if (Object.keys(this.cache).length > (this.maxCacheElements - 1)) {
cacheKeysOrdered = Object.keys(this.cache).sort(function (a, b) {
return _this.cache[a].date.getDate() - _this.cache[b].date.getDate();
});
delete this.cache[cacheKeysOrdered[0]];
}
// Before returning new result, save it in cache
this.cache[originalSearchText] = {
date: new Date(),
results: matches,
};
return [2 /*return*/, matches];
}
});
});
};
Cockatoo.prototype.getScore = function (search, patterns, options) {
var score;
var minDistance;
var patternMatch;
for (var i = 0; i < patterns.length; i++) {
var distance = this.getMinDistance(search, patterns[i], options);
if (search.length === 0 || minDistance < 0) {
console.error('Error computing score of:', search, 'on pattern', patterns[i]);
return { score: 0, patternMatch: '' };
}
else {
if (minDistance === undefined || distance < minDistance) {
minDistance = distance;
patternMatch = patterns[i];
}
}
}
score = 100 - 100 * minDistance / search.length;
return { score: score, patternMatch: patternMatch };
};
Cockatoo.prototype.getTokenScore = function (tokens, patternTokens, originalTokens, originalPatternTokens) {
var tokensAgregatedLength = tokens
.map(function (token) { return token.length; })
.reduce(function (prev, curr) { return prev + curr; });
var totalDistance = 0;
var tokenScore = 0;
var tokenMatches = [];
for (var i = 0; i < tokens.length; i++) {
var minTokenDistance = void 0;
var patternTokenMatch = void 0;
for (var j = 0; j < patternTokens.length; j++) {
var minDistance = this.getMinDistance(tokens[i], patternTokens[j], this.options);
if (tokens[i].length === 0 || minDistance < 0) {
console.error('Error computing score of:', originalTokens[i], 'on pattern', originalPatternTokens[j]);
return { tokenScore: tokenScore, tokenMatches: [] };
}
else {
if (minTokenDistance === undefined || minDistance < minTokenDistance) {
minTokenDistance = minDistance;
patternTokenMatch = originalPatternTokens[j];
}
}
}
totalDistance += minTokenDistance;
tokenScore = 100 - minTokenDistance / tokens[i].length * 100;
tokenMatches.push(new tokenMatch_1.TokenMatch({
searchToken: originalTokens[i],
patternToken: patternTokenMatch,
score: tokenScore,
completeness: utils_1.getCompleteness(tokens[i], patternTokenMatch, tokenScore)
}));
}
tokenScore = 100 - 100 * totalDistance / tokensAgregatedLength;
return { tokenScore: tokenScore, tokenMatches: tokenMatches };
};
Cockatoo.prototype.getMinDistance = function (search, pattern, options) {
if (!pattern) {
return search.length;
}
var min = -1;
if (!options.exhaustive) {
if (search.length < pattern.length) {
min = Math.min(this.damLev.getDistance(search, pattern.slice(0, search.length)), this.damLev.getDistance(search, pattern));
}
else {
min = this.damLev.getDistance(search, pattern);
}
}
else {
if (search.length < pattern.length) {
for (var len = search.length; len <= pattern.length; len++) {
for (var i = 0; i < pattern.length - len + 1; i++) {
var s1 = search;
var s2 = pattern.slice(i, i + len);
var currentDistance = this.damLev.getDistance(s1, s2);
if (min === -1 || currentDistance < min) {
min = currentDistance;
}
}
}
}
else if (search.length >= pattern.length) {
var currentDistance = this.damLev.getDistance(search, pattern);
if (min === -1 || currentDistance < min) {
min = currentDistance;
}
}
}
return min;
};
Cockatoo.prototype.getMatch = function (searchText, searchTextTokens, originalSearchTextTokens, index) {
return __awaiter(this, void 0, void 0, function () {
var score, patternMatch, completeness, match, scoreResult, _a, tokenScore, tokenMatches;
return __generator(this, function (_b) {
// If tokenize is not active or search or pattern are multi-tokened, we get score and completeness.
if (!this.options.tokenize || (searchTextTokens.length > 1 || this.searchableTokensList[index].length > 1)) {
scoreResult = this.getScore(searchText, this.searchableValuesList[index], this.options);
score = scoreResult.score;
patternMatch = scoreResult.patternMatch;
completeness = utils_1.getCompleteness(searchText, patternMatch, score);
}
// If tokenize is active, we get tokenScore. If also, search and pattern are single-tokened, we assign score and completeness from token.
if (this.options.tokenize) {
_a = this.getTokenScore(searchTextTokens, this.searchableTokensList[index], originalSearchTextTokens, this.originalTokensList[index]), tokenScore = _a.tokenScore, tokenMatches = _a.tokenMatches;
if (score === undefined) {
score = tokenScore;
completeness = tokenMatches[0].completeness;
}
// If score or tokenScore are above its threshold, we create the match object.
if (score >= this.options.threshold || tokenScore >= (this.options.tokenThreshold || this.options.threshold)) {
match = new match_1.Match({
item: this.elementsList[index],
score: score,
completeness: completeness,
tokenScore: tokenScore,
tokenMatches: tokenMatches,
});
}
}
else if (score >= this.options.threshold) {
// If not tokenized, and score is above its threshold, we create the match object.
match = new match_1.Match({
item: this.elementsList[index],
score: score,
completeness: completeness
});
}
return [2 /*return*/, match];
});
});
};
Cockatoo.prototype.generateValuesList = function (elementsList, options) {
var _a;
var valuesList = [];
if (typeof elementsList[0] === 'string') {
for (var i = 0; i < elementsList.length; i++) {
valuesList[i] = [elementsList[i]];
}
}
else {
for (var i = 0; i < elementsList.length; i++) {
valuesList[i] = [];
for (var j = 0; j < options.keys.length; j++) {
if (Array.isArray(elementsList[i][options.keys[j]])) {
(_a = valuesList[i]).push.apply(_a, elementsList[i][options.keys[j]]);
}
else {
valuesList[i].push(elementsList[i][options.keys[j]] || undefined);
}
}
}
}
return valuesList
.filter(function (values) {
return values.filter(function (value) {
return value !== undefined && value !== null;
});
});
};
Cockatoo.prototype.generateTokensList = function (valuesList) {
var tokensList = [];
for (var i = 0; i < valuesList.length; i++) {
var currentElementTokens = [];
for (var j = 0; j < valuesList[i].length; j++) {
currentElementTokens.push.apply(currentElementTokens, this.getTokensFromText(valuesList[i][j]));
}
tokensList[i] = currentElementTokens;
}
return tokensList;
};
Cockatoo.prototype.getTokensFromText = function (text) {
if (text) {
return text
.split(' ')
.filter(function (token) { return token !== ''; });
}
else {
return [];
}
};
return Cockatoo;
}());
exports.Cockatoo = Cockatoo;