UNPKG

cmpstr

Version:

CmpStr is a lightweight, fast and well performing package for calculating string similarity

9 lines (8 loc) 39.7 kB
/** * CmpStr v3.0.3 build-462b952-250813 * This is a lightweight, fast and well performing library for calculating string similarity. * (c) 2023-2025 Paul Köhler @komed3 / MIT License * Visit https://github.com/komed3/cmpstr and https://npmjs.org/package/cmpstr */ const e=e=>e.replace(/\[(\d+)]/g,".$1").split(".").map(e=>/^\d+$/.test(e)?+e:e);function t(r,s,n){if(""===s)return n;const[i,...a]=e(s);if(void 0!==r&&("object"!=typeof r||null===r))throw Error(`Cannot set property <${i}> of <${JSON.stringify(r)}>`);return Object.assign(r??("number"==typeof i?[]:Object.create(null)),{[i]:t(r?.[i],a.join("."),n)})}function r(e=Object.create(null),t=Object.create(null),s=!1){return Object.keys(t).forEach(n=>{const i=t[n];(s||void 0!==i)&&"__proto__"!==n&&"constructor"!==n&&(e[n]="object"!=typeof i||Array.isArray(i)?i:r("object"!=typeof e[n]||Array.isArray(e[n])?Object.create(null):e[n],i))}),e}class s{static ENV;static instance;store=new Set;totalTime=0;totalMem=0;active;static detectEnv(){"undefined"!=typeof process?s.ENV="nodejs":"undefined"!=typeof performance?s.ENV="browser":s.ENV="unknown"}static getInstance(e){return s.ENV||s.detectEnv(),s.instance||(s.instance=new s(e)),s.instance}constructor(e){this.active=e??!1}now(){switch(s.ENV){case"nodejs":return Number(process.hrtime.bigint())/1e6;case"browser":return performance.now();default:return Date.now()}}mem(){switch(s.ENV){case"nodejs":return process.memoryUsage().heapUsed;case"browser":return performance.memory?.usedJSHeapSize??0;default:return 0}}enable(){this.active=!0}disable(){this.active=!1}clear(){this.store.clear(),this.totalTime=0,this.totalMem=0}run(e,t={}){if(!this.active)return e();const r=this.now(),s=this.mem(),n=e(),i=this.now()-r,a=this.mem()-s;return this.store.add({time:i,mem:a,res:n,meta:t}),this.totalTime+=i,this.totalMem+=a,n}async runAsync(e,t={}){if(!this.active)return await e();const r=this.now(),s=this.mem(),n=await e(),i=this.now()-r,a=this.mem()-s;return this.store.add({time:i,mem:a,res:n,meta:t}),this.totalTime+=i,this.totalMem+=a,n}getAll(){return[...this.store]}getLast(){return this.getAll().pop()}getTotal(){return{time:this.totalTime,mem:this.totalMem}}services={enable:this.enable.bind(this),disable:this.disable.bind(this),clear:this.clear.bind(this),report:this.getAll.bind(this),last:this.getLast.bind(this),total:this.getTotal.bind(this)}}class n{text;words=[];sentences=[];charFrequency=new Map;wordHistogram=new Map;syllableCache=new Map;constructor(e){this.text=e.trim(),this.tokenize(),this.computeFrequencies()}tokenize(){this.words=[],this.sentences=[];const e=this.text,t=/\p{L}+/gu;let r;for(;null!==(r=t.exec(e));)this.words.push(r[0].toLowerCase());this.sentences=e.split(/(?<=[.!?])\s+/).filter(Boolean)}computeFrequencies(){for(const e of this.text)this.charFrequency.set(e,(this.charFrequency.get(e)??0)+1);for(const e of this.words)this.wordHistogram.set(e,(this.wordHistogram.get(e)??0)+1)}estimateSyllables(e){if(this.syllableCache.has(e))return this.syllableCache.get(e);const t=e.toLowerCase().replace(/[^a-zäöüß]/g,"").match(/[aeiouyäöü]+/g),r=t?t.length:1;return this.syllableCache.set(e,r),r}getLength(){return this.text.length}getWordCount(){return this.words.length}getSentenceCount(){return this.sentences.length}getAvgWordLength(){let e=0;for(const t of this.words)e+=t.length;return this.words.length?e/this.words.length:0}getAvgSentenceLength(){return this.sentences.length?this.words.length/this.sentences.length:0}getWordHistogram(){return Object.fromEntries(this.wordHistogram)}getMostCommonWords(e=5){return[...this.wordHistogram.entries()].sort((e,t)=>t[1]-e[1]).slice(0,e).map(e=>e[0])}getHapaxLegomena(){return[...this.wordHistogram.entries()].filter(([,e])=>1===e).map(e=>e[0])}hasNumbers(){return/\d/.test(this.text)}getUpperCaseRatio(){let e=0,t=0;for(let r=0,s=this.text.length;r<s;r++){const s=this.text[r];/[A-Za-zÄÖÜäöüß]/.test(s)&&(t++,/[A-ZÄÖÜ]/.test(s)&&e++)}return t?e/t:0}getCharFrequency(){return Object.fromEntries(this.charFrequency)}getUnicodeStats(){const e={};for(const[t,r]of this.charFrequency){const s=t.charCodeAt(0).toString(16).padStart(4,"0").toUpperCase();e[s]=(e[s]??0)+r}return e}getLongWordRatio(e=7){let t=0;for(const r of this.words)r.length>=e&&t++;return this.words.length?t/this.words.length:0}getShortWordRatio(e=3){let t=0;for(const r of this.words)r.length<=e&&t++;return this.words.length?t/this.words.length:0}getSyllablesCount(){let e=0;for(const t of this.words)e+=this.estimateSyllables(t);return e}getMonosyllabicWordCount(){let e=0;for(const t of this.words)1===this.estimateSyllables(t)&&e++;return e}getMinSyllablesWordCount(e){let t=0;for(const r of this.words)this.estimateSyllables(r)>=e&&t++;return t}getMaxSyllablesWordCount(e){let t=0;for(const r of this.words)this.estimateSyllables(r)<=e&&t++;return t}getHonoresR(){return 100*Math.log(this.words.length)/(1-this.getHapaxLegomena().length/(this.wordHistogram.size??1))}getReadingTime(e=200){return Math.max(1,this.words.length/(e??1))}getReadabilityScore(e="flesch"){const t=this.words.length||1,r=t/(this.sentences.length||1),s=(this.getSyllablesCount()||1)/t;switch(e){case"flesch":return 206.835-1.015*r-84.6*s;case"fleschde":return 180-r-58.5*s;case"kincaid":return.39*r+11.8*s-15.59}}getLIXScore(){const e=this.words.length||1;return e/(this.sentences.length||1)+this.getLongWordRatio()*e/e*100}getWSTFScore(){const e=this.words.length||1,t=this.getMinSyllablesWordCount(3)/e*100,r=this.getAvgSentenceLength(),s=100*this.getLongWordRatio();return[.1935*t+.1672*r+.1297*s-this.getMonosyllabicWordCount()/e*100*.0327-.875,.2007*t+.1682*r+.1373*s-2.779,.2963*t+.1905*r-1.1144,.2744*t+.2656*r-1.693]}}class i{a;b;options;entries=[];grouped=[];diffRun=!1;constructor(e,t,r={}){this.a=e,this.b=t,this.options={mode:"word",caseInsensitive:!1,contextLines:1,groupedLines:!0,expandLines:!1,showChangeMagnitude:!0,maxMagnitudeSymbols:5,lineBreak:"\n",...r},this.computeDiff()}text2lines(){const e=this.a.trim().split(/\r?\n/),t=this.b.trim().split(/\r?\n/);return{linesA:e,linesB:t,maxLen:Math.max(e.length,t.length)}}tokenize(e){const{mode:t}=this.options;switch(t){case"line":return[e];case"word":return e.split(/\s+/)}}concat(e){const{mode:t}=this.options;return e.join("word"===t?" ":"")}computeDiff(){if(!this.diffRun){const{linesA:e,linesB:t,maxLen:r}=this.text2lines();for(let s=0;s<r;s++){const r=e[s]||"",n=t[s]||"";this.lineDiff(r,n,s)}this.findGroups(),this.diffRun=!0}}lineDiff(e,t,r){const{mode:s,caseInsensitive:n}=this.options,i=Math.max(e.length,t.length);let a=e,o=t;n&&(a=e.toLowerCase(),o=t.toLowerCase());let c=[],l=0,h=0;if("line"===s)a!==o&&(c.push({posA:0,posB:0,del:e,ins:t,size:t.length-e.length}),l=e.length,h=t.length);else{c=this.preciseDiff(e,a,t,o);for(const e of c)l+=e.del.length,h+=e.ins.length}c.length&&this.entries.push({line:r,diffs:c,delSize:l,insSize:h,baseLen:i,totalSize:h-l,magnitude:this.magnitude(l,h,i)})}preciseDiff(e,t,r,s){const n=e=>e.reduce((t,r,s)=>(t.push(s?t[s-1]+e[s-1].length+1:0),t),[]),i=this.tokenize(e),a=this.tokenize(r),o=this.tokenize(t),c=this.tokenize(s),l=o.length,h=c.length,p=n(i),u=n(a),d=[];let g=0,m=0;for(;g<l&&m<h;)if(o[g]===c[m]){let e=1;for(;g+e<l&&m+e<h&&o[g+e]===c[m+e];)e++;d.push({ai:g,bi:m,len:e}),g+=e,m+=e}else{let e=!1;for(let t=1;t<=3&&!e;t++)g+t<l&&o[g+t]===c[m]?(d.push({ai:g+t,bi:m,len:1}),g+=t+1,m+=1,e=!0):m+t<h&&o[g]===c[m+t]&&(d.push({ai:g,bi:m+t,len:1}),g+=1,m+=t+1,e=!0);e||(g++,m++)}const f=[];let y=0,w=0;for(const e of d){if(y<e.ai||w<e.bi){const t=i.slice(y,e.ai),r=a.slice(w,e.bi);f.push({posA:p[y]??0,posB:u[w]??0,del:this.concat(t),ins:this.concat(r),size:r.join("").length-t.join("").length})}y=e.ai+e.len,w=e.bi+e.len}if(y<l||w<h){const e=i.slice(y),t=a.slice(w);f.push({posA:p[y]??0,posB:u[w]??0,del:this.concat(e),ins:this.concat(t),size:t.join("").length-e.join("").length})}return f.filter(e=>e.del.length>0||e.ins.length>0)}findGroups(){const{contextLines:e}=this.options,t=(e,t,r)=>{const[s,n,i,a]=["delSize","insSize","totalSize","baseLen"].map(t=>e.reduce((e,r)=>e+r[t],0));this.grouped.push({start:t,end:r,delSize:s,insSize:n,totalSize:i,line:e[0].line,entries:e,magnitude:this.magnitude(s,n,a)})};let r=[],s=0,n=0;for(const i of this.entries){const a=Math.max(0,i.line-e),o=i.line+e;!r.length||a<=n+1?(r.length||(s=a),n=Math.max(n,o),r.push(i)):(t(r,s,n),r=[i],s=a,n=o)}r.length&&t(r,s,n)}magnitude(e,t,r){const{maxMagnitudeSymbols:s}=this.options,n=e+t;if(0===n||0===r)return"";const i=Math.min(s,Math.max(Math.round(n/r*s),1)),a=Math.round(t/n*i),o=i-a;return"+".repeat(a)+"-".repeat(o)}output(e){const{mode:t,contextLines:r,groupedLines:s,expandLines:n,showChangeMagnitude:i,lineBreak:a}=this.options,{linesA:o,linesB:c,maxLen:l}=this.text2lines(),h=Math.max(4,l.toString().length),p=(t,r)=>e?`[${r}m${t}`:t,u=t=>e?`${t}`:`-[${t}]`,d=t=>e?`${t}`:`+[${t}]`,g=(e,t,r,s)=>{s&&m(s);for(let s=e;s<=t;s++)f(s,r??s);w.push("")},m=e=>{var t;w.push(`${" ".repeat(h)} ${t=`@@ -${e.line+1},${e.delSize} +${e.line+1},${e.insSize} @@`,p(t,"36")} ${i?(e=>p(e,"33"))(e.magnitude):""}`)},f=(e,t)=>{if(o[e]||c[e]){const s=this.entries.find(t=>t.line===e),n=(e+1).toString().padStart(h," ");s&&t===e?(w.push(`${n} ${r=`- ${y(o[e],s.diffs,"del")}`,p(r,"31")}`),w.push(`${" ".repeat(h)} ${(e=>p(e,"32"))(`+ ${y(c[e],s.diffs,"ins")}`)}`)):w.push(`${n} ${(e=>p(e,"90"))(o[e])}`)}var r},y=(e,r,s)=>{if(!r.length||"line"===t)return e;let n="",i=0;for(const t of r){const r="del"===s?t.posA:t.posB,a="del"===s?t.del:t.ins;a&&(r>i&&(n+=e.slice(i,r)),n+="del"===s?u(a):d(a),i=r+a.length)}return n+e.slice(i)};let w=[""];switch(!0){case n:g(0,l);break;case s:for(const e of this.grouped)g(e.start,e.end,void 0,e);break;default:for(const e of this.entries)g(e.line-r,e.line+r,e.line,e)}return w.join(a)}getStructuredDiff(){return this.entries}getGroupedDiff(){return this.grouped}getASCIIDiff(){return this.output(!1)}getCLIDiff(){return this.output(!0)}}class a{static FNV_PRIME=16777619;static HASH_OFFSET=2166136261;static fnv1a(e){const t=e.length;let r=this.HASH_OFFSET;const s=Math.floor(t/4);for(let t=0;t<s;t++){const s=4*t;r^=e.charCodeAt(s)|e.charCodeAt(s+1)<<8|e.charCodeAt(s+2)<<16|e.charCodeAt(s+3)<<24,r*=this.FNV_PRIME}const n=t%4;if(n>0){const t=4*s;for(let s=0;s<n;s++)r^=e.charCodeAt(t+s),r*=this.FNV_PRIME}return r^=r>>>16,r*=2246822507,r^=r>>>13,r*=3266489909,r^=r>>>16,r>>>0}}class o{static MAX_LEN=2048;static TABLE_SIZE=1e4;table=new Map;key(e,t,r=!1){for(const e of t)if(e.length>o.MAX_LEN)return!1;const s=t.map(e=>a.fnv1a(e));return r&&s.sort(),[e,...s].join("-")}has(e){return this.table.has(e)}get(e){return this.table.get(e)}set(e,t,r=!0){return!(!(this.table.size<o.TABLE_SIZE)||!r&&this.table.has(e)||(this.table.set(e,t),0))}delete(e){this.table.delete(e)}clear(){this.table.clear()}size(){return this.table.size}}class c{static pipeline=new Map;static cache=new o;static getPipeline(e){if(c.pipeline.has(e))return c.pipeline.get(e);const t=[];e.includes("d")&&t.push(e=>e.normalize("NFD")),e.includes("u")&&t.push(e=>e.normalize("NFC")),e.includes("x")&&t.push(e=>e.normalize("NFKC")),e.includes("w")&&t.push(e=>e.replace(/\s+/g," ")),e.includes("t")&&t.push(e=>e.trim()),e.includes("r")&&t.push(e=>e.replace(/(.)\1+/g,"$1")),e.includes("s")&&t.push(e=>e.replace(/[^\p{L}\p{N}\s]/gu,"")),e.includes("k")&&t.push(e=>e.replace(/[^\p{L}]/gu,"")),e.includes("n")&&t.push(e=>e.replace(/\p{N}/gu,"")),e.includes("i")&&t.push(e=>e.toLowerCase());const r=e=>{let r=e;for(const e of t)r=e(r);return r};return c.pipeline.set(e,r),r}static normalize(e,t){if(Array.isArray(e))return e.map(e=>c.normalize(e,t));if(!t||"string"!=typeof t||!e)return e;const r=c.cache.key(t,[e]);if(r&&c.cache.has(r))return c.cache.get(r);const s=c.getPipeline(t)(e);return r&&c.cache.set(r,s),s}static async normalizeAsync(e,t){return await(Array.isArray(e)?Promise.all(e.map(e=>c.normalize(e,t))):Promise.resolve(c.normalize(e,t)))}static clear(){c.pipeline.clear(),c.cache.clear()}}class l{static filters=new Map;static find(e,t){return l.filters.get(e)?.find(e=>e.id===t)}static add(e,t,r,s={}){const{priority:n=10,active:i=!0,overrideable:a=!0}=s,o=l.filters.get(e)??[],c=o.findIndex(e=>e.id===t);if(c>=0){if(!o[c].overrideable)return!1;o.splice(c,1)}return o.push({id:t,fn:r,priority:n,active:i,overrideable:a}),o.sort((e,t)=>e.priority-t.priority),l.filters.set(e,o),!0}static remove(e,t){const r=l.filters.get(e);if(!r)return!1;const s=r.findIndex(e=>e.id===t);return s>=0&&(r.splice(s,1),!0)}static pause(e,t){const r=l.find(e,t);return!!r&&(r.active=!1,!0)}static resume(e,t){const r=l.find(e,t);return!!r&&(r.active=!0,!0)}static list(e,t=!1){const r=l.filters.get(e)??[],s=[];for(const e of r)t&&!e.active||s.push(e.id);return s}static apply(e,t){const r=l.filters.get(e);if(!r||r.every(e=>!e.active))return t;const s=e=>{for(const t of r)t.active&&(e=t.fn(e));return e};return Array.isArray(t)?t.map(s):s(t)}static async applyAsync(e,t){const r=l.filters.get(e);if(!r||r.every(e=>!e.active))return t;const s=async e=>{for(const t of r)t.active&&(e=await Promise.resolve(t.fn(e)));return e};return Array.isArray(t)?Promise.all(t.map(s)):s(t)}static clear(e){e?l.filters.delete(e):l.filters.clear()}}const h=Object.create(null),p=Object.create(null);function u(e,t){if(e in h||e in p)throw new Error(`Registry <${e}> already exists / overwriting is forbidden`);const r=Object.create(null),s={add(s,n,i=!1){if(!(n.prototype instanceof t))throw new TypeError(`Class must extend <${e}>`);if(!i&&s in r)throw new Error(`Entry <${s}> already exists / use <update=true> to overwrite`);r[s]=n},remove(e){delete r[e]},has:e=>e in r,list:()=>Object.keys(r),get(t){if(!(t in r))throw new Error(`Class <${t}> not registered for <${e}>`);return r[t]}};return h[e]=s,p[e]=(t,...r)=>function(e,t,...r){t=function(e,t){if(!(e in h))throw new ReferenceError(`Registry <${e}> does not exist`);return"string"==typeof t?h[e]?.get(t):t}(e,t);try{return new t(...r)}catch(e){throw new Error(`Cannot instantiate class <${t}>`,{cause:e})}}(e,t,...r),s}const d=s.getInstance();class g{static cache=new o;metric;a;b;origA=[];origB=[];options;symmetric;results;static clear(){this.cache.clear()}static swap(e,t,r,s){return r>s?[t,e,s,r]:[e,t,r,s]}static clamp(e){return Math.max(0,Math.min(1,e))}constructor(e,t,r,s={},n=!1){if(this.metric=e,this.a=Array.isArray(t)?t:[t],this.b=Array.isArray(r)?r:[r],0===this.a.length||0===this.b.length)throw new Error("Inputs <a> and <b> must not be empty");this.options=s,this.symmetric=n}preCompute(e,t,r,s){return e===t?{res:1}:0==r||0==s||r<2&&s<2?{res:0}:void 0}compute(e,t,r,s,n){throw new Error("Method compute() must be overridden in a subclass")}runSingle(e,t){let r=String(this.a[e]),s=r,n=String(this.b[t]),i=n,a=s.length,o=i.length,c=this.preCompute(s,i,a,o);return c||(c=d.run(()=>{const e=g.cache.key(this.metric,[s,i],this.symmetric);return g.cache.get(e||"")??(()=>{this.symmetric&&([s,i,a,o]=g.swap(s,i,a,o));const t=this.compute(s,i,a,o,Math.max(a,o));return e&&g.cache.set(e,t),t})()})),{metric:this.metric,a:this.origA[e]??r,b:this.origB[t]??n,...c}}async runSingleAsync(e,t){return Promise.resolve(this.runSingle(e,t))}runBatch(){const e=[];for(let t=0;t<this.a.length;t++)for(let r=0;r<this.b.length;r++)e.push(this.runSingle(t,r));this.results=e}async runBatchAsync(){const e=[];for(let t=0;t<this.a.length;t++)for(let r=0;r<this.b.length;r++)e.push(await this.runSingleAsync(t,r));this.results=e}runPairwise(){const e=[];for(let t=0;t<this.a.length;t++)e.push(this.runSingle(t,t));this.results=e}async runPairwiseAsync(){const e=[];for(let t=0;t<this.a.length;t++)e.push(await this.runSingleAsync(t,t));this.results=e}setOriginal(e,t){return e&&(this.origA=Array.isArray(e)?e:[e]),t&&(this.origB=Array.isArray(t)?t:[t]),this}isBatch(){return this.a.length>1||this.b.length>1}isSingle(){return!this.isBatch()}isPairwise(e=!1){return!(!this.isBatch()||this.a.length!==this.b.length)||!e&&(()=>{throw new Error("Mode <pairwise> requires arrays of equal length")})()}isSymmetrical(){return this.symmetric}whichMode(e){return e??this.options?.mode??"default"}clear(){this.results=void 0}run(e,t=!0){switch(t&&this.clear(),this.whichMode(e)){case"default":if(this.isSingle()){this.results=this.runSingle(0,0);break}case"batch":this.runBatch();break;case"single":this.results=this.runSingle(0,0);break;case"pairwise":this.isPairwise()&&this.runPairwise();break;default:throw new Error(`Unsupported mode <${e}>`)}}async runAsync(e,t=!0){switch(t&&this.clear(),this.whichMode(e)){case"default":if(this.isSingle()){this.results=await this.runSingleAsync(0,0);break}case"batch":await this.runBatchAsync();break;case"single":this.results=await this.runSingleAsync(0,0);break;case"pairwise":this.isPairwise()&&await this.runPairwiseAsync();break;default:throw new Error(`Unsupported async mode <${e}>`)}}getMetricName(){return this.metric}getResults(){if(void 0===this.results)throw new Error("run() must be called before getResult()");return this.results}}const m=u("metric",g);class f{maxSize;buffers=[];pointer=0;constructor(e){this.maxSize=e}acquire(e,t){const r=this.buffers.length;for(let s=0;s<r;s++){const n=(this.pointer+s)%r,i=this.buffers[n];if(i.size>=e)return this.pointer=(n+1)%r,t||i.size===e?i:null}return null}release(e){this.buffers.length<this.maxSize?this.buffers.push(e):(this.buffers[this.pointer]=e,this.pointer=(this.pointer+1)%this.maxSize)}clear(){this.buffers=[],this.pointer=0}}class y{static CONFIG={uint16:{type:"uint16",maxSize:32,maxItemSize:2048,allowOversize:!0},"number[]":{type:"number[]",maxSize:16,maxItemSize:1024,allowOversize:!1},set:{type:"set",maxSize:8,maxItemSize:0,allowOversize:!1},map:{type:"map",maxSize:8,maxItemSize:0,allowOversize:!1}};static POOLS={uint16:new f(32),"number[]":new f(16),set:new f(8),map:new f(8)};static allocate(e,t){switch(e){case"uint16":return new Uint16Array(t);case"number[]":return new Array(t).fill(0);case"set":return new Set;case"map":return new Map}}static acquire(e,t){const r=this.CONFIG[e];if(t>r.maxItemSize)return this.allocate(e,t);const s=this.POOLS[e].acquire(t,r.allowOversize);return s?"uint16"===e?s.buffer.subarray(0,t):s.buffer:this.allocate(e,t)}static acquireMany(e,t){return t.map(t=>this.acquire(e,t))}static release(e,t,r){r<=this.CONFIG[e].maxItemSize&&this.POOLS[e].release({buffer:t,size:r})}}m.add("cosine",class extends g{constructor(e,t,r={}){super("cosine",e,t,r,!0)}_termFreq(e,t){const r=e.split(t),s=y.acquire("map",r.length);for(const e of r)s.set(e,(s.get(e)||0)+1);return s}compute(e,t){const{delimiter:r=" "}=this.options,s=this._termFreq(e,r),n=this._termFreq(t,r);let i=0,a=0,o=0;for(const[e,t]of s)i+=t*(n.get(e)||0),a+=t*t;for(const e of n.values())o+=e*e;return a=Math.sqrt(a),o=Math.sqrt(o),y.release("map",s,s.size),y.release("map",n,n.size),{res:a&&o?g.clamp(i/(a*o)):0,raw:{dotProduct:i,magnitudeA:a,magnitudeB:o}}}}),m.add("damerau",class extends g{constructor(e,t,r={}){super("damerau",e,t,r,!0)}compute(e,t,r,s,n){const i=r+1,[a,o,c]=y.acquireMany("uint16",[i,i,i]);for(let e=0;e<=r;e++)o[e]=e;for(let n=1;n<=s;n++){c[0]=n;const s=t.charCodeAt(n-1);for(let i=1;i<=r;i++){const r=e.charCodeAt(i-1),l=r===s?0:1;let h=Math.min(c[i-1]+1,o[i]+1,o[i-1]+l);i>1&&n>1&&r===t.charCodeAt(n-2)&&s===e.charCodeAt(i-2)&&(h=Math.min(h,a[i-2]+l)),c[i]=h}a.set(o),o.set(c)}const l=o[r];return y.release("uint16",a,i),y.release("uint16",o,i),y.release("uint16",c,i),{res:0===n?1:g.clamp(1-l/n),raw:{dist:l,maxLen:n}}}}),m.add("dice",class extends g{constructor(e,t,r={}){super("dice",e,t,r,!0)}_bigrams(e){const t=e.length-1,r=y.acquire("set",t);for(let s=0;s<t;s++)r.add(e.substring(s,s+2));return r}compute(e,t){const r=this._bigrams(e),s=this._bigrams(t);let n=0;for(const e of r)s.has(e)&&n++;const i=r.size,a=s.size,o=i+a;return y.release("set",r,i),y.release("set",s,a),{res:0===o?1:g.clamp(2*n/o),raw:{intersection:n,size:o}}}}),m.add("hamming",class extends g{constructor(e,t,r={}){super("hamming",e,t,r,!0)}compute(e,t,r,s,n){if(r!==s){if(void 0===this.options.pad)throw new Error(`Strings must be of equal length for Hamming Distance, a=${r} and b=${s} given, use option.pad for automatic adjustment`);r<n&&(e=e.padEnd(n,this.options.pad)),s<n&&(t=t.padEnd(n,this.options.pad)),r=s=n}let i=0;for(let r=0;r<e.length;r++)e[r]!==t[r]&&i++;return{res:0===r?1:g.clamp(1-i/r),raw:{dist:i}}}}),m.add("jaccard",class extends g{constructor(e,t,r={}){super("jaccard",e,t,r,!0)}compute(e,t,r,s){const[n,i]=y.acquireMany("set",[r,s]);for(const t of e)n.add(t);for(const e of t)i.add(e);let a=0;for(const e of n)i.has(e)&&a++;const o=n.size+i.size-a;return y.release("set",n,r),y.release("set",i,s),{res:0===o?1:g.clamp(a/o),raw:{intersection:a,union:o}}}}),m.add("jaroWinkler",class extends g{constructor(e,t,r={}){super("jaro-winkler",e,t,r,!0)}compute(e,t,r,s){const n=Math.max(0,Math.floor(s/2)-1),i=y.acquire("uint16",r),a=y.acquire("uint16",s);for(let e=0;e<r;e++)i[e]=0;for(let e=0;e<s;e++)a[e]=0;let o=0;for(let c=0;c<r;c++){const r=Math.max(0,c-n),l=Math.min(c+n+1,s);for(let s=r;s<l;s++)if(!a[s]&&e[c]===t[s]){i[c]=1,a[s]=1,o++;break}}let c=0,l=0,h=0,p=0;if(o>0){let n=0;for(let s=0;s<r;s++)if(i[s]){for(;!a[n];)n++;e[s]!==t[n]&&c++,n++}c/=2,l=(o/r+o/s+(o-c)/o)/3;for(let n=0;n<Math.min(4,r,s)&&e[n]===t[n];n++)h++;p=l+.1*h*(1-l)}return y.release("uint16",i,r),y.release("uint16",a,s),{res:g.clamp(p),raw:{matchWindow:n,matches:o,transpos:c,jaro:l,prefix:h}}}}),m.add("lcs",class extends g{constructor(e,t,r={}){super("lcs",e,t,r,!0)}compute(e,t,r,s,n){const i=r+1,[a,o]=y.acquireMany("uint16",[i,i]);for(let e=0;e<=r;e++)a[e]=0;for(let n=1;n<=s;n++){o[0]=0;const s=t.charCodeAt(n-1);for(let t=1;t<=r;t++)e.charCodeAt(t-1)===s?o[t]=a[t-1]+1:o[t]=Math.max(a[t],o[t-1]);a.set(o)}const c=a[r];return y.release("uint16",a,i),y.release("uint16",o,i),{res:0===n?1:g.clamp(c/n),raw:{lcs:c,maxLen:n}}}}),m.add("levenshtein",class extends g{constructor(e,t,r={}){super("levenshtein",e,t,r,!0)}compute(e,t,r,s,n){const i=r+1,[a,o]=y.acquireMany("uint16",[i,i]);for(let e=0;e<=r;e++)a[e]=e;for(let n=1;n<=s;n++){o[0]=n;const s=t.charCodeAt(n-1);for(let t=1;t<=r;t++){const r=e.charCodeAt(t-1)===s?0:1;o[t]=Math.min(o[t-1]+1,a[t]+1,a[t-1]+r)}a.set(o)}const c=a[r];return y.release("uint16",a,i),y.release("uint16",o,i),{res:0===n?1:g.clamp(1-c/n),raw:{dist:c,maxLen:n}}}}),m.add("needlemanWunsch",class extends g{constructor(e,t,r={}){super("needlemanWunsch",e,t,r,!0)}compute(e,t,r,s,n){const{match:i=1,mismatch:a=-1,gap:o=-1}=this.options,c=r+1,[l,h]=y.acquireMany("uint16",[c,c]);l[0]=0;for(let e=1;e<=r;e++)l[e]=l[e-1]+o;for(let n=1;n<=s;n++){h[0]=l[0]+o;const s=t.charCodeAt(n-1);for(let t=1;t<=r;t++){const r=e.charCodeAt(t-1)===s?i:a;h[t]=Math.max(l[t-1]+r,l[t]+o,h[t-1]+o)}l.set(h)}const p=l[r];y.release("uint16",l,c),y.release("uint16",h,c);const u=n*i;return{res:0===u?0:g.clamp(p/u),raw:{score:p,denum:u}}}}),m.add("qGram",class extends g{constructor(e,t,r={}){super("qgram",e,t,r,!0)}_qGrams(e,t){const r=Math.max(0,e.length-t+1),s=y.acquire("set",r);for(let n=0;n<r;n++)s.add(e.slice(n,n+t));return s}compute(e,t){const{q:r=2}=this.options,s=this._qGrams(e,r),n=this._qGrams(t,r);let i=0;for(const e of s)n.has(e)&&i++;const a=s.size,o=n.size,c=Math.max(a,o);return y.release("set",s,a),y.release("set",n,o),{res:0===c?1:g.clamp(i/c),raw:{intersection:i,size:c}}}}),m.add("smithWaterman",class extends g{constructor(e,t,r={}){super("smithWaterman",e,t,r,!0)}compute(e,t,r,s){const{match:n=2,mismatch:i=-1,gap:a=-2}=this.options,o=r+1,[c,l]=y.acquireMany("uint16",[o,o]);for(let e=0;e<=r;e++)c[e]=0;let h=0;for(let o=1;o<=s;o++){l[0]=0;const s=t.charCodeAt(o-1);for(let t=1;t<=r;t++){const r=e.charCodeAt(t-1)===s?n:i;l[t]=Math.max(0,c[t-1]+r,c[t]+a,l[t-1]+a),l[t]>h&&(h=l[t])}c.set(l)}y.release("uint16",c,o),y.release("uint16",l,o);const p=Math.min(r*n,s*n);return{res:0===p?0:g.clamp(h/p),raw:{score:h,denum:p}}}});const w=s.getInstance();class b{static cache=new o;static default;algo;options;map;static clear(){this.cache.clear()}constructor(e,t={}){const s=this.constructor.default??{},n=t.map??s.map;if(!n)throw new Error("No mapping specified for phonetic algorithm");const i=A.get(e,n);if(void 0===i)throw new Error(`Requested mapping <${n}> is not declared`);this.options=r(r(s,i.options??{}),t),this.algo=e,this.map=i}applyPattern(e){const{patterns:t=[]}=this.map;if(!t||!t.length)return e;for(const{pattern:r,replace:s,all:n=!1}of t)e=e[n?"replaceAll":"replace"](r,s);return e}applyRules(e,t,r,s){const{ruleset:n=[]}=this.map;if(!n||!n.length)return;const i=r[t-1]||"",a=r[t-2]||"",o=r[t+1]||"",c=r[t+2]||"";for(const l of n)if((!l.char||l.char===e)&&("start"!==l.position||0===t)&&!("middle"===l.position&&t>0&&t<s)&&("end"!==l.position||t===s)&&(!l.prev||l.prev.includes(i))&&(!l.prevNot||!l.prevNot.includes(i))&&(!l.prev2||l.prev2.includes(a))&&(!l.prev2Not||!l.prev2Not.includes(a))&&(!l.next||l.next.includes(o))&&(!l.nextNot||!l.nextNot.includes(o))&&(!l.next2||l.next2.includes(c))&&(!l.next2Not||!l.next2Not.includes(c))&&(!l.leading||l.leading.includes(r.slice(0,l.leading.length).join("")))&&(!l.trailing||l.trailing.includes(r.slice(-l.trailing.length).join("")))&&(!l.match||l.match.every((e,s)=>r[t+s]===e)))return l.code}encode(e){const{map:t={},ignore:r=[]}=this.map;e=this.applyPattern(e);const s=this.word2Chars(e),n=s.length;let i="",a=null;for(let e=0;e<n;e++){const o=s[e];if(r.includes(o))continue;const c=this.mapChar(o,e,s,n,a,t);if(void 0!==c&&(i+=c,a=c,this.exitEarly(i,e)))break}return this.adjustCode(i,s)}mapChar(e,t,r,s,n,i){const{dedupe:a=!0,fallback:o}=this.options,c=this.applyRules(e,t,r,s)??i[e]??o;return a&&c===n?void 0:c}equalLen(e){const{length:t=-1,pad:r="0"}=this.options;return-1===t?e:(e+r.repeat(t)).slice(0,t)}word2Chars(e){return e.toLowerCase().split("")}exitEarly(e,t){const{length:r=-1}=this.options;return r>0&&e.length>=r}adjustCode(e,t){return e}loop(e){const t=[];for(const r of e){const e=b.cache.key(this.algo,[r]),s=b.cache.get(e||"")??(()=>{const t=this.encode(r);return e&&b.cache.set(e,t),t})();s&&s.length&&t.push(this.equalLen(s))}return t}async loopAsync(e){const t=[];for(const r of e){const e=await Promise.resolve(this.encode(r));e&&e.length&&t.push(this.equalLen(e))}return t}getAlgoName(){return this.algo}getIndex(e){const{delimiter:t=" "}=this.options;return w.run(()=>this.loop(e.split(t).filter(Boolean)).filter(Boolean))}async getIndexAsync(e){const{delimiter:t=" "}=this.options;return(await w.runAsync(async()=>await this.loopAsync(e.split(t).filter(Boolean)))).filter(Boolean)}}const x=u("phonetic",b),A=(()=>{const e=Object.create(null),t=t=>e[t]||=Object.create(null);return{add(e,r,s,n=!1){const i=t(e);if(!n&&r in i)throw new Error(`Entry <${r}> already exists / use <update=true> to overwrite`);i[r]=s},remove(e,r){delete t(e)[r]},has:(e,r)=>r in t(e),get:(e,r)=>t(e)[r],list:e=>Object.keys(t(e))}})();x.add("caverphone",class extends b{static default={map:"en2",delimiter:" ",length:-1,pad:"",dedupe:!1};constructor(e={}){super("caverphone",e)}encode(e){return e=e.replace(/[^A-Z]/gi,"").toLowerCase(),super.encode(e)}mapChar(e){return e}adjustCode(e){return e.toUpperCase()}}),A.add("caverphone","en1",{options:{length:6,pad:"1"},map:{},patterns:[{pattern:/^(c|r|t|en)ough/,replace:"$1ou2f"},{pattern:/^gn/,replace:"2n"},{pattern:/mb$/,replace:"m2"},{pattern:/cq/g,replace:"2q"},{pattern:/c(e|i|y)/g,replace:"s$1"},{pattern:/tch/g,replace:"2ch"},{pattern:/[cqx]/g,replace:"k"},{pattern:/v/g,replace:"f"},{pattern:/dg/g,replace:"2g"},{pattern:/ti(a|o)/g,replace:"si$1"},{pattern:/d/g,replace:"t"},{pattern:/ph/g,replace:"fh"},{pattern:/b/g,replace:"p"},{pattern:/sh/g,replace:"s2"},{pattern:/z/g,replace:"s"},{pattern:/^[aeiou]/,replace:"A"},{pattern:/[aeiou]/g,replace:"3"},{pattern:/3gh3/g,replace:"3kh3"},{pattern:/gh/g,replace:"22"},{pattern:/g/g,replace:"k"},{pattern:/s+/g,replace:"S"},{pattern:/t+/g,replace:"T"},{pattern:/p+/g,replace:"P"},{pattern:/k+/g,replace:"K"},{pattern:/f+/g,replace:"F"},{pattern:/m+/g,replace:"M"},{pattern:/n+/g,replace:"N"},{pattern:/j/g,replace:"y"},{pattern:/l3/g,replace:"L3"},{pattern:/r3/g,replace:"R3"},{pattern:/w3/g,replace:"W3"},{pattern:/y3/g,replace:"Y3"},{pattern:/ly/g,replace:"Ly"},{pattern:/ry/g,replace:"Ry"},{pattern:/wy/g,replace:"Wy"},{pattern:/wh3/g,replace:"Wh3"},{pattern:/why/g,replace:"Why"},{pattern:/^h/,replace:"A"},{pattern:/[hlrwy23]/g,replace:""}]}),A.add("caverphone","en2",{options:{length:10,pad:"1"},map:{},patterns:[{pattern:/e$/,replace:""},{pattern:/^(c|r|t|en|tr)ough/,replace:"$1ou2f"},{pattern:/^gn/,replace:"2n"},{pattern:/mb$/,replace:"m2"},{pattern:/cq/g,replace:"2q"},{pattern:/c(e|i|y)/g,replace:"s$1"},{pattern:/tch/g,replace:"2ch"},{pattern:/[cqx]/g,replace:"k"},{pattern:/v/g,replace:"f"},{pattern:/dg/g,replace:"2g"},{pattern:/ti(a|o)/g,replace:"si$1"},{pattern:/d/g,replace:"t"},{pattern:/ph/g,replace:"fh"},{pattern:/b/g,replace:"p"},{pattern:/sh/g,replace:"s2"},{pattern:/z/g,replace:"s"},{pattern:/^[aeiou]/,replace:"A"},{pattern:/[aeiou]/g,replace:"3"},{pattern:/j/g,replace:"y"},{pattern:/^y3/,replace:"Y3"},{pattern:/^y/,replace:"A"},{pattern:/y/g,replace:"3"},{pattern:/3gh3/g,replace:"3kh3"},{pattern:/gh/g,replace:"22"},{pattern:/g/g,replace:"k"},{pattern:/s+/g,replace:"S"},{pattern:/t+/g,replace:"T"},{pattern:/p+/g,replace:"P"},{pattern:/k+/g,replace:"K"},{pattern:/f+/g,replace:"F"},{pattern:/m+/g,replace:"M"},{pattern:/n+/g,replace:"N"},{pattern:/l3/g,replace:"L3"},{pattern:/r3/g,replace:"R3"},{pattern:/w3/g,replace:"W3"},{pattern:/wh3/g,replace:"Wh3"},{pattern:/[lrw]$/,replace:"3"},{pattern:/^h/,replace:"A"},{pattern:/3$/,replace:"A"},{pattern:/[hlrw23]/g,replace:""}]}),x.add("cologne",class extends b{static default={map:"default",delimiter:" ",length:-1,dedupe:!0};constructor(e={}){super("cologne",e)}adjustCode(e){return e.slice(0,1)+e.slice(1).replaceAll("0","")}}),A.add("cologne","default",{map:{a:"0","ä":"0",e:"0",i:"0",j:"0",o:"0","ö":"0",u:"0","ü":"0",y:"0",b:"1",p:"1",d:"2",t:"2",f:"3",v:"3",w:"3",g:"4",k:"4",q:"4",l:"5",m:"6",n:"6",r:"7",c:"8",s:"8","ß":"8",z:"8",x:"48"},ignore:["h"],ruleset:[{char:"p",next:["h"],code:"3"},{char:"c",position:"start",next:["a","h","k","l","o","q","r","u","x"],code:"4"},{char:"c",next:["a","h","k","o","q","u","x"],prevNot:["s","z"],code:"4"},{char:"d",next:["c","s","z"],code:"8"},{char:"t",next:["c","s","z"],code:"8"},{char:"x",prev:["c","k","q"],code:"8"}]}),x.add("metaphone",class extends b{static default={map:"en90",delimiter:" ",length:-1,pad:"",dedupe:!1};constructor(e={}){super("metaphone",e)}encode(e){return e=e.replace(/([A-BD-Z])\1+/gi,(e,t)=>"C"===t?e:t),super.encode(e)}adjustCode(e){return e.slice(0,1)+e.slice(1).replace(/[AEIOU]/g,"")}}),A.add("metaphone","en90",{map:{a:"A",b:"B",c:"K",d:"T",e:"E",f:"F",g:"K",h:"H",i:"I",j:"J",k:"K",l:"L",m:"M",n:"N",o:"O",p:"P",q:"K",r:"R",s:"S",t:"T",u:"U",v:"F",w:"W",x:"KS",y:"Y",z:"S"},ruleset:[{char:"a",position:"start",next:["e"],code:""},{char:"g",position:"start",next:["n"],code:""},{char:"k",position:"start",next:["n"],code:""},{char:"p",position:"start",next:["n"],code:""},{char:"w",position:"start",next:["r"],code:""},{char:"b",position:"end",prev:["m"],code:""},{char:"c",next:["h"],prevNot:["s"],code:"X"},{char:"c",next:["i"],next2:["a"],code:"X"},{char:"c",next:["e","i","y"],code:"S"},{char:"d",next:["g"],next2:["e","i","y"],code:"J"},{char:"g",next:["h"],next2Not:["","a","e","i","o","u"],code:""},{char:"g",trailing:"n",code:""},{char:"g",trailing:"ned",code:""},{char:"g",next:["e","i","y"],prevNot:["g"],code:"J"},{char:"h",prev:["a","e","i","o","u"],nextNot:["a","e","i","o","u"],code:""},{char:"h",prev:["c","g","p","s","t"],code:""},{char:"k",prev:["c"],code:""},{char:"p",next:["h"],code:"F"},{char:"s",next:["h"],code:"X"},{char:"s",next:["i"],next2:["a","o"],code:"X"},{char:"t",next:["i"],next2:["a","o"],code:"X"},{char:"t",next:["h"],code:"0"},{char:"t",next:["c"],next2:["h"],code:""},{char:"w",nextNot:["a","e","i","o","u"],code:""},{char:"h",leading:"w",code:""},{char:"x",position:"start",code:"S"},{char:"y",nextNot:["a","e","i","o","u"],code:""}]}),x.add("soundex",class extends b{static default={map:"en",delimiter:" ",length:4,pad:"0",dedupe:!0};constructor(e={}){super("soundex",e)}adjustCode(e,t){return t[0].toUpperCase()+e.slice(1).replaceAll("0","")}}),A.add("soundex","en",{map:{a:"0",e:"0",h:"0",i:"0",o:"0",u:"0",w:"0",y:"0",b:"1",f:"1",p:"1",v:"1",c:"2",g:"2",j:"2",k:"2",q:"2",s:"2",x:"2",z:"2",d:"3",t:"3",l:"4",m:"5",n:"5",r:"6"}}),A.add("soundex","de",{map:{a:"0","ä":"0",e:"0",h:"0",i:"0",j:"0",o:"0","ö":"0",u:"0","ü":"0",y:"0",b:"1",f:"1",p:"1",v:"1",w:"1",c:"2",g:"2",k:"2",q:"2",s:"2","ß":"2",x:"2",z:"2",d:"3",t:"3",l:"4",m:"5",n:"5",r:"6"},ruleset:[{char:"c",next:["h"],code:"7"}]});const v=s.getInstance();class S{static filter={add:l.add,remove:l.remove,pause:l.pause,resume:l.resume,list:l.list,clear:l.clear};static metric={add:m.add,remove:m.remove,has:m.has,list:m.list};static phonetic={add:x.add,remove:x.remove,has:x.has,list:x.list,map:{add:A.add,remove:A.remove,has:A.has,list:A.list}};static profiler=v.services;static clearCache={normalizer:c.clear,metric:g.clear,phonetic:b.clear};static analyze(e){return new n(e)}static diff(e,t,r){return new i(e,t,r)}static create(e){return new S(e)}options=Object.create(null);constructor(e){e&&("string"==typeof e?this.setSerializedOptions(e):this.setOptions(e))}assert(e,t){switch(e){case"metric":if(!S.metric.has(t))throw new Error("CmpStr <metric> must be set, call .setMetric(), use CmpStr.metric.list() for available metrics");break;case"phonetic":if(!S.phonetic.has(t))throw new Error("CmpStr <phonetic> must be set, call .setPhonetic(), use CmpStr.phonetic.list() for available phonetic algorithms");break;default:throw new Error(`Cmpstr condition <${e}> unknown`)}}assertMany(...e){for(const[t,r]of e)this.assert(t,r)}resolveOptions(e){return r({...this.options??Object.create(null)},e)}normalize(e,t){return c.normalize(e,t??this.options.flags??"")}filter(e,t){return l.apply(t,e)}prepare(e,t){const{flags:r,processors:s}=t??this.options;return r?.length&&(e=this.normalize(e,r)),e=this.filter(e,"input"),s?.phonetic&&(e=this.index(e,s.phonetic)),e}postProcess(e,t){return t?.removeZero&&Array.isArray(e)&&(e=e.filter(e=>e.res>0)),e}index(e,{algo:t,opt:r}){this.assert("phonetic",t);const s=p.phonetic(t,r),n=r?.delimiter??" ";return Array.isArray(e)?e.map(e=>s.getIndex(e).join(n)):s.getIndex(e).join(n)}compute(e,t,r,s,n,i){const a=this.resolveOptions(r);this.assert("metric",a.metric);const o=i?e:this.prepare(e,a),c=i?t:this.prepare(t,a);if(a.safeEmpty&&(Array.isArray(o)&&0===o.length||Array.isArray(c)&&0===c.length||""===o||""===c))return[];const l=p.metric(a.metric,o,c,a.opt);"prep"!==a.output&&l.setOriginal(e,t),l.run(s);const h=this.postProcess(l.getResults(),a);return this.output(h,n??a.raw)}output(e,t){return t??this.options.raw?e:Array.isArray(e)?e.map(e=>({source:e.a,target:e.b,match:e.res})):{source:e.a,target:e.b,match:e.res}}clone(){return Object.assign(Object.create(Object.getPrototypeOf(this)),this)}reset(){for(const e in this.options)delete this.options[e];return this}setOptions(e){return this.options=e,this}mergeOptions(e){return r(this.options,e),this}setSerializedOptions(e){return this.options=JSON.parse(e),this}setOption(e,r){return t(this.options,e,r),this}rmvOption(t){return function(t,r,s=!1){const n=(e,t,r=0)=>{const i=t[r];if(!e||"object"!=typeof e)return!1;if(r===t.length-1)return delete e[i];if(!n(e[i],t,r+1))return!1;if(!s){const t=e[i];"object"==typeof t&&(Array.isArray(t)&&t.every(e=>null==e)||!Array.isArray(t)&&0===Object.keys(t).length)&&delete e[i]}return!0};n(t,e(r))}(this.options,t),this}setRaw(e){return this.setOption("raw",e)}setMetric(e){return this.setOption("metric",e)}setFlags(e){return this.setOption("flags",e)}rmvFlags(){return this.rmvOption("flags")}setProcessors(e){return this.setOption("processors",e)}rmvProcessors(){return this.rmvOption("processors")}getOptions(){return this.options}getSerializedOptions(){return JSON.stringify(this.options)}getOption(t){return function(t,r){return e(r).reduce((e,t)=>e?.[t]??void 0,t)}(this.options,t)}test(e,t,r){return this.compute(e,t,r,"single")}compare(e,t,r){return this.compute(e,t,r,"single",!0).res}batchTest(e,t,r){return this.compute(e,t,r,"batch")}batchSorted(e,t,r="desc",s){return this.output(this.compute(e,t,s,"batch",!0).sort((e,t)=>"asc"===r?e.res-t.res:t.res-e.res),s?.raw??this.options.raw)}pairs(e,t,r){return this.compute(e,t,r,"pairwise")}match(e,t,r,s){return this.output(this.compute(e,t,s,"batch",!0).filter(e=>e.res>=r).sort((e,t)=>t.res-e.res),s?.raw??this.options.raw)}closest(e,t,r=1,s){return this.batchSorted(e,t,"desc",s).slice(0,r)}furthest(e,t,r=1,s){return this.batchSorted(e,t,"asc",s).slice(0,r)}search(e,t,r,s){const n=this.resolveOptions({flags:r,processors:s}),i=this.prepare(e,n),a=this.prepare(t,n);return t.filter((e,t)=>a[t].includes(i))}matrix(e,t){return(e=this.prepare(e,this.resolveOptions(t))).map(t=>this.compute(t,e,void 0,"batch",!0,!0).map(e=>e.res??0))}phoneticIndex(e,t,r){const{algo:s,opt:n}=this.options.processors?.phonetic??{};return this.index(e,{algo:t??s,opt:r??n})}}class z extends S{static create(e){return new z(e)}constructor(e){super(e)}async normalizeAsync(e,t){return c.normalizeAsync(e,t??this.options.flags??"")}async filterAsync(e,t){return l.applyAsync(t,e)}async prepareAsync(e,t){const{flags:r,processors:s}=t??this.options;return r?.length&&(e=await this.normalizeAsync(e,r)),e=await this.filterAsync(e,"input"),s?.phonetic&&(e=await this.indexAsync(e,s.phonetic)),e}async indexAsync(e,{algo:t,opt:r}){this.assert("phonetic",t);const s=p.phonetic(t,r),n=r?.delimiter??" ";return Array.isArray(e)?Promise.all(e.map(e=>s.getIndexAsync(e).then(e=>e.join(n)))):s.getIndexAsync(e).then(e=>e.join(n))}async computeAsync(e,t,r,s,n,i){const a=this.resolveOptions(r);this.assert("metric",a.metric);const o=i?e:await this.prepareAsync(e,a),c=i?t:await this.prepareAsync(t,a);if(a.safeEmpty&&(Array.isArray(o)&&0===o.length||Array.isArray(c)&&0===c.length||""===o||""===c))return[];const l=p.metric(a.metric,o,c,a.opt);"prep"!==a.output&&l.setOriginal(e,t),await l.runAsync(s);const h=this.postProcess(l.getResults(),a);return this.output(h,n??a.raw)}async testAsync(e,t,r){return this.computeAsync(e,t,r,"single")}async compareAsync(e,t,r){return(await this.computeAsync(e,t,r,"single",!0)).res}async batchTestAsync(e,t,r){return this.computeAsync(e,t,r,"batch")}async batchSortedAsync(e,t,r="desc",s){const n=await this.computeAsync(e,t,s,"batch",!0);return this.output(n.sort((e,t)=>"asc"===r?e.res-t.res:t.res-e.res),s?.raw??this.options.raw)}async pairsAsync(e,t,r){return this.computeAsync(e,t,r,"pairwise")}async matchAsync(e,t,r,s){const n=await this.computeAsync(e,t,s,"batch",!0);return this.output(n.filter(e=>e.res>=r).sort((e,t)=>t.res-e.res),s?.raw??this.options.raw)}async closestAsync(e,t,r=1,s){return(await this.batchSortedAsync(e,t,"desc",s)).slice(0,r)}async furthestAsync(e,t,r=1,s){return(await this.batchSortedAsync(e,t,"asc",s)).slice(0,r)}async searchAsync(e,t,r,s){const n=this.resolveOptions({flags:r,processors:s}),i=await this.prepareAsync(e,n),a=await this.prepareAsync(t,n);return t.filter((e,t)=>a[t].includes(i))}async matrixAsync(e,t){return e=await this.prepareAsync(e,this.resolveOptions(t)),Promise.all(e.map(async t=>await this.computeAsync(t,e,void 0,"batch",!0,!0).then(e=>e.map(e=>e.res??0))))}async phoneticIndexAsync(e,t,r){const{algo:s,opt:n}=this.options.processors?.phonetic??{};return this.indexAsync(e,{algo:t??s,opt:r??n})}}export{S as CmpStr,z as CmpStrAsync,i as DiffChecker,c as Normalizer,n as TextAnalyzer}; //# sourceMappingURL=CmpStr.esm.min.js.map