@@ -57,24 +57,49 @@ export class Util {
57
57
} ) ;
58
58
} ;
59
59
public static diffPercentage = (
60
- newInput : string ,
61
- oldInput : string
60
+ str1 : string ,
61
+ str2 : string
62
62
) : number => {
63
- const firstArray = oldInput . split ( "" ) ;
64
- const secondArray = newInput . split ( "" ) ;
65
-
66
- const biggestArray =
67
- firstArray . length > secondArray . length ? firstArray : secondArray ;
68
- const smallestArray =
69
- secondArray === biggestArray ? firstArray : secondArray ;
63
+ const matchDestructively = ( str1 = '' , str2 = '' ) => {
64
+ str1 = str1 . toLowerCase ( ) ;
65
+ str2 = str2 . toLowerCase ( ) ;
66
+ let arr = new Array ( ) ;
67
+ for ( let i = 0 ; i <= str1 . length ; i ++ ) {
68
+ let lastValue = i ;
69
+ for ( let j = 0 ; j <= str2 . length ; j ++ ) {
70
+ if ( i === 0 ) {
71
+ arr [ j ] = j ;
72
+ } else if ( j > 0 ) {
73
+ let newValue = arr [ j - 1 ] ;
74
+ if ( str1 . charAt ( i - 1 ) !== str2 . charAt ( j - 1 ) ) {
75
+ newValue = Math . min ( Math . min ( newValue , lastValue ) , arr [ j ] ) + 1 ;
76
+ }
77
+ arr [ j - 1 ] = lastValue ; lastValue = newValue ;
78
+ }
79
+ }
80
+ if ( i > 0 ) {
81
+ arr [ str2 . length ] = lastValue ;
82
+ }
83
+ }
84
+ return arr [ str2 . length ] ;
85
+ } ;
70
86
71
- let count = 0 ;
72
- for ( const letter of smallestArray ) {
73
- if ( biggestArray . includes ( letter ) ) {
74
- count ++ ;
87
+ const calculateSimilarity = ( str1 = '' , str2 = '' ) => {
88
+ // Get the length of the strings
89
+ let longer = str1 ;
90
+ let shorter = str2 ;
91
+ if ( str1 . length < str2 . length ) {
92
+ longer = str2 ; shorter = str1 ;
75
93
}
76
- }
94
+ let longerLength = longer . length ;
95
+ if ( longerLength === 0 ) {
96
+ return 1 ;
97
+ }
98
+ // Calculate the edit distance
99
+ return + ( ( longerLength - matchDestructively ( longer , shorter ) ) / longerLength * 100 ) . toFixed ( 2 ) ;
100
+ } ;
77
101
78
- return Math . floor ( ( count / biggestArray . length ) * 100 ) ;
79
- } ;
102
+
103
+ return calculateSimilarity ( str1 , str2 ) ;
104
+ }
80
105
}
0 commit comments