]>
git.immae.eu Git - perso/Immae/Projets/Cryptomonnaies/BIP39.git/blob - src/js/levenshtein.js
2 // https://github.com/hiddentao/fast-levenshtein/blob/2.0.6/levenshtein.js
8 collator
= (typeof Intl
!== "undefined" && typeof Intl
.Collator
!== "undefined") ? Intl
.Collator("generic", { sensitivity: "base" }) : null;
10 console
.log("Collator could not be initialized and wouldn't be used");
17 * Based on the algorithm at http://en.wikipedia.org/wiki/Levenshtein_distance.
21 * Calculate levenshtein distance of the two strings.
23 * @param str1 String the first string.
24 * @param str2 String the second string.
25 * @param [options] Additional options.
26 * @param [options.useCollator] Use `Intl.Collator` for locale-sensitive string comparison.
27 * @return Integer the levenshtein distance (0 and above).
29 get: function(str1
, str2
, options
) {
30 var useCollator
= (options
&& collator
&& options
.useCollator
);
32 var str1Len
= str1
.length
,
33 str2Len
= str2
.length
;
36 if (str1Len
=== 0) return str2Len
;
37 if (str2Len
=== 0) return str1Len
;
40 var curCol
, nextCol
, i
, j
, tmp
;
42 // initialise previous row
43 for (i
=0; i
<str2Len
; ++i
) {
45 str2Char
[i
] = str2
.charCodeAt(i
);
47 prevRow
[str2Len
] = str2Len
;
51 // calculate current row distance from previous row using collator
52 for (i
= 0; i
< str1Len
; ++i
) {
55 for (j
= 0; j
< str2Len
; ++j
) {
59 strCmp
= 0 === collator
.compare(str1
.charAt(i
), String
.fromCharCode(str2Char
[j
]));
61 nextCol
= prevRow
[j
] + (strCmp
? 0 : 1);
69 tmp
= prevRow
[j
+ 1] + 1;
74 // copy current col value into previous (in preparation for next iteration)
78 // copy last col value into previous (in preparation for next iteration)
83 // calculate current row distance from previous row without collator
84 for (i
= 0; i
< str1Len
; ++i
) {
87 for (j
= 0; j
< str2Len
; ++j
) {
91 strCmp
= str1
.charCodeAt(i
) === str2Char
[j
];
93 nextCol
= prevRow
[j
] + (strCmp
? 0 : 1);
101 tmp
= prevRow
[j
+ 1] + 1;
106 // copy current col value into previous (in preparation for next iteration)
110 // copy last col value into previous (in preparation for next iteration)
111 prevRow
[j
] = nextCol
;
120 if (typeof define
!== "undefined" && define
!== null && define
.amd
) {
126 else if (typeof module
!== "undefined" && module
!== null && typeof exports
!== "undefined" && module
.exports
=== exports
) {
127 module
.exports
= Levenshtein
;
130 else if (typeof self
!== "undefined" && typeof self
.postMessage
=== 'function' && typeof self
.importScripts
=== 'function') {
131 self
.Levenshtein
= Levenshtein
;
133 // browser main thread
134 else if (typeof window
!== "undefined" && window
!== null) {
135 window
.Levenshtein
= Levenshtein
;