[READ-ONLY] Mirror of https://github.com/FoxxMD/string-sameness. Compare the sameness of two strings
foxxmd.github.io/string-sameness/
compare
cosine-similarity
dice-coefficient
levenshtein-distance
sameness
string
text
typescript
1.2 kB
36 lines
1import leven from "leven";
2import {ComparisonStrategy, ComparisonStrategyResultObject} from "../atomic.js";
3
4export const calculateLevenSimilarity = (valA: string, valB: string) => {
5 let longer: string;
6 let shorter: string;
7 if (valA.length > valB.length) {
8 longer = valA;
9 shorter = valB;
10 } else {
11 longer = valB;
12 shorter = valA;
13 }
14
15 const distance = leven(longer, shorter);
16 // use the shorter length
17 // because if we have more move/change operations than the length of the shortest string than we have two unique strings
18 // and if we use the longer length the score actually gets *better* as the length gap gets larger (not what we want)
19 // -- cap at 100% diff
20 const diff = Math.min((distance / shorter.length) * 100, 100);
21 return [distance, 100 - diff];
22}
23
24const stratFunc = (valA: string, valB: string) => {
25 const res = calculateLevenSimilarity(valA, valB);
26 return {
27 rawScore: res[0],
28 distance: res[0],
29 score: res[1]
30 };
31}
32
33export const levenStrategy: ComparisonStrategy<ComparisonStrategyResultObject> = {
34 name: 'leven',
35 strategy: stratFunc
36}