Code coverage report for master/levenshtein.js

Statements: 100% (25 / 25)      Branches: 100% (12 / 12)      Functions: 100% (1 / 1)      Lines: 100% (23 / 23)      Ignored: none     

All files » master/ » levenshtein.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 531         1   14 14     14 10     6     6 56       6 55   55 500     500   500 500 166     500 500 198       500       55     6    
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;
};