X-Git-Url: http://www.aleph1.co.uk/gitweb/?a=blobdiff_plain;ds=sidebyside;f=node_modules%2Funderscore.string%2Flevenshtein.js;fp=node_modules%2Funderscore.string%2Flevenshtein.js;h=85f220c1f2848a7f04dd0d2631e729b8dbd1c887;hb=a2bd1bf0c2c1f1a17d188f4dc0726a45494cefae;hp=0000000000000000000000000000000000000000;hpb=57c063afa3f66b07c4bbddc2d6129a96d90f0aad;p=yaffs-website diff --git a/node_modules/underscore.string/levenshtein.js b/node_modules/underscore.string/levenshtein.js new file mode 100644 index 000000000..85f220c1f --- /dev/null +++ b/node_modules/underscore.string/levenshtein.js @@ -0,0 +1,52 @@ +var makeString = require('./helper/makeString'); + +/** + * Based on the implementation here: https://github.com/hiddentao/fast-levenshtein + */ +module.exports = function levenshtein(str1, str2) { + 'use strict'; + str1 = makeString(str1); + str2 = makeString(str2); + + // Short cut cases + if (str1 === str2) return 0; + if (!str1 || !str2) return Math.max(str1.length, str2.length); + + // two rows + var prevRow = new Array(str2.length + 1); + + // initialise previous row + for (var i = 0; i < prevRow.length; ++i) { + prevRow[i] = i; + } + + // calculate current row distance from previous row + for (i = 0; i < str1.length; ++i) { + var nextCol = i + 1; + + for (var j = 0; j < str2.length; ++j) { + var curCol = nextCol; + + // substution + nextCol = prevRow[j] + ( (str1.charAt(i) === str2.charAt(j)) ? 0 : 1 ); + // insertion + var tmp = curCol + 1; + if (nextCol > tmp) { + nextCol = tmp; + } + // deletion + tmp = prevRow[j + 1] + 1; + if (nextCol > tmp) { + nextCol = tmp; + } + + // copy current col value into previous (in preparation for next iteration) + prevRow[j] = curCol; + } + + // copy last col value into previous (in preparation for next iteration) + prevRow[j] = nextCol; + } + + return nextCol; +};