fuzzy-regex
Version:
A regular expression library for Node.js that allows for a configurable number of mismatches (fuzzy matching), powered by the high-performance [TRE](https://laurikari.net/tre/) regex engine. This package supports both ESM and CommonJS, and provides a simp
60 lines (59 loc) • 1.77 kB
JavaScript
// src/tre.ts
import { createRequire } from "module";
var require2 = createRequire(import.meta.url);
var path = "./tre.node";
var addon = require2(path);
var TreLib;
if (typeof addon === "object") {
TreLib = addon.Tre;
}
if (typeof addon === "string") {
TreLib = require2(addon).Tre;
}
if (!TreLib) {
throw new Error("Failed to load tre");
}
var Tre = TreLib;
// src/index.ts
function fuzzyRegex(pattern, options) {
const patternString = pattern instanceof RegExp ? pattern.source : pattern;
let insensitive = true;
if (options?.caseInsensitive !== void 0) {
insensitive = options.caseInsensitive;
} else if (pattern instanceof RegExp) {
insensitive = pattern.ignoreCase;
}
if (options?.caseInsensitive !== void 0 && pattern instanceof RegExp && pattern.ignoreCase !== options.caseInsensitive) {
throw new Error("Case sensitivity mismatch");
}
const tre = new Tre(patternString, insensitive);
function getOptions(str) {
const min = Math.min(str.length, patternString.length);
const defaultMaxErrs = Math.floor(min / 10) + (min % 10 > 5 ? 1 : 0);
return {
costIns: options?.costIns ?? 1,
costDel: options?.costDel ?? 1,
costSubst: options?.costSubst ?? 1,
maxCost: options?.maxCost ?? defaultMaxErrs,
maxIns: options?.maxIns ?? defaultMaxErrs,
maxDel: options?.maxDel ?? defaultMaxErrs,
maxSubst: options?.maxSubst ?? defaultMaxErrs,
maxErr: options?.maxErr ?? defaultMaxErrs
};
}
return {
test: (str) => {
return tre.fuzzy(str, getOptions(str));
},
exec: (str) => {
return tre.fuzzyExec(str, getOptions(str));
},
toString: () => {
return patternString;
}
};
}
export {
fuzzyRegex
};
//# sourceMappingURL=index.js.map