@imranbarbhuiya/mongoose-fuzzy-searching
Version:
Mongoose fuzzy searching plugin
76 lines (75 loc) • 2.55 kB
JavaScript
;
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
if (ar || !(i in from)) {
if (!ar) ar = Array.prototype.slice.call(from, 0, i);
ar[i] = from[i];
}
}
return to.concat(ar || Array.prototype.slice.call(from));
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.makeNGrams = exports.nGrams = void 0;
var utils_1 = require("./utils");
var addWholePhrase = function (arr, text) {
if (text.split(" ").length > 1) {
return __spreadArray(__spreadArray([], arr, true), [text.toLowerCase()], false);
}
return arr;
};
/**
* Creates sequence of characters taken from the given string.
* @param text - The string for the sequence.
* @param minSize - Lower limit to start creating sequence.
* @param prefixOnly -Only return ngrams from start of word.
* @return The sequence of characters in array of strings.
*/
var nGrams = function (text, minSize, prefixOnly) {
if (prefixOnly === void 0) { prefixOnly = false; }
var set = new Set();
var index;
if (minSize <= 0) {
throw new Error("minSize must be greater than 0.");
}
if (!text) {
return [];
}
text = text.toLowerCase();
index = prefixOnly ? 0 : text.length - minSize + 1;
if (text.length <= minSize) {
return [text];
}
if (prefixOnly) {
while (minSize < text.length + 1) {
set.add(text.slice(index, index + minSize));
minSize++;
}
return Array.from(set);
}
while (minSize <= text.length + 1) {
if (index !== 0) {
set.add(text.slice(--index, index + minSize));
}
else {
minSize++;
index = text.length - minSize + 1;
}
}
return Array.from(set);
};
exports.nGrams = nGrams;
var makeNGrams = function (_a) {
var text = _a.text, escapeSpecialCharacters = _a.escapeSpecialCharacters, minSize = _a.minSize, prefixOnly = _a.prefixOnly;
if (!text) {
return [];
}
var result = text
.split(" ")
.map(function (q) {
var cleanText = (0, utils_1.replaceSymbols)(q, escapeSpecialCharacters);
return (0, exports.nGrams)(cleanText, minSize, prefixOnly);
})
.reduce(function (acc, arr) { return acc.concat(arr); }, []);
return addWholePhrase(Array.from(new Set(result)), text);
};
exports.makeNGrams = makeNGrams;