romaji-fuzzy-search
Version:
Generates a regular expression for "Romaji Fuzzy Search"
49 lines (48 loc) • 1.9 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.convertToRegExp = exports.romajiDictionary = exports.indexedRomajiDictionary = void 0;
const romaji_dictionary_1 = require("./romaji-dictionary");
exports.indexedRomajiDictionary = romaji_dictionary_1.indexedRomajiDictionary;
var romaji_dictionary_2 = require("./romaji-dictionary");
Object.defineProperty(exports, "romajiDictionary", { enumerable: true, get: function () { return romaji_dictionary_2.romajiDictionary; } });
/**
* @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#escaping
*/
const escapeRegExp = (str) => {
return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
};
const convertToRegExp = (str, indexedDictionary = exports.indexedRomajiDictionary) => {
const createRomajiPattern = (romajiDictionaryItem) => `(?:${romajiDictionaryItem.map(escapeRegExp).join('|')})`;
let pointer = 0;
let result = '';
let firstCharacter = undefined;
while (firstCharacter = str[pointer]) {
if (firstCharacter === undefined) {
break;
}
let phrase = firstCharacter;
if (str[pointer + 1]) {
phrase += str[pointer + 1];
}
if (str[pointer + 2]) {
phrase += str[pointer + 2];
}
let replaced = false;
for (let phraseLength = 3; phraseLength >= 1; phraseLength--) {
const replacement = indexedDictionary[phrase.slice(0, phraseLength)];
if (replacement) {
result += createRomajiPattern(replacement);
pointer += phraseLength;
replaced = true;
break;
}
}
if (replaced) {
continue;
}
result += escapeRegExp(firstCharacter);
pointer++;
}
return result;
};
exports.convertToRegExp = convertToRegExp;