6 collator = (typeof Intl !== "undefined" && typeof Intl.Collator !== "undefined") ? Intl.Collator("generic", { sensitivity: "base" }) : null;
8 console.log("Collator could not be initialized and wouldn't be used");
15 * Based on the algorithm at http://en.wikipedia.org/wiki/Levenshtein_distance.
19 * Calculate levenshtein distance of the two strings.
21 * @param str1 String the first string.
22 * @param str2 String the second string.
23 * @param [options] Additional options.
24 * @param [options.useCollator] Use `Intl.Collator` for locale-sensitive string comparison.
25 * @return Integer the levenshtein distance (0 and above).
27 get: function(str1, str2, options) {
28 var useCollator = (options && collator && options.useCollator);
30 var str1Len = str1.length,
31 str2Len = str2.length;
34 if (str1Len === 0) return str2Len;
35 if (str2Len === 0) return str1Len;
38 var curCol, nextCol, i, j, tmp;
40 // initialise previous row
41 for (i=0; i<str2Len; ++i) {
43 str2Char[i] = str2.charCodeAt(i);
45 prevRow[str2Len] = str2Len;
49 // calculate current row distance from previous row using collator
50 for (i = 0; i < str1Len; ++i) {
53 for (j = 0; j < str2Len; ++j) {
57 strCmp = 0 === collator.compare(str1.charAt(i), String.fromCharCode(str2Char[j]));
59 nextCol = prevRow[j] + (strCmp ? 0 : 1);
67 tmp = prevRow[j + 1] + 1;
72 // copy current col value into previous (in preparation for next iteration)
76 // copy last col value into previous (in preparation for next iteration)
81 // calculate current row distance from previous row without collator
82 for (i = 0; i < str1Len; ++i) {
85 for (j = 0; j < str2Len; ++j) {
89 strCmp = str1.charCodeAt(i) === str2Char[j];
91 nextCol = prevRow[j] + (strCmp ? 0 : 1);
99 tmp = prevRow[j + 1] + 1;
104 // copy current col value into previous (in preparation for next iteration)
108 // copy last col value into previous (in preparation for next iteration)
109 prevRow[j] = nextCol;
118 if (typeof define !== "undefined" && define !== null && define.amd) {
124 else if (typeof module !== "undefined" && module !== null && typeof exports !== "undefined" && module.exports === exports) {
125 module.exports = Levenshtein;
128 else if (typeof self !== "undefined" && typeof self.postMessage === 'function' && typeof self.importScripts === 'function') {
129 self.Levenshtein = Levenshtein;
131 // browser main thread
132 else if (typeof window !== "undefined" && window !== null) {
133 window.Levenshtein = Levenshtein;