levenshtein.js 1.04 KB
/*
   Copyright (c) 2006. All Rights reserved.

   If you use this script, please email me and let me know, thanks!
   Andrew Hedges
   andrew (at) hedges (dot) name
   If you want to hire me to write JavaScript for you, see my resume.

	http://andrew.hedges.name/resume/
*/

// return the smallest of the three values passed in
function minimum (x, y, z)
{
	if (x < y && x < z) return x;
	if (y < x && y < z) return y;
	return z;
}

// calculate the Levenshtein distance between a and b,
function levenshtein (a, b)
{
	var cost;
	var m = a.length;
	var n = b.length;

	// make sure a.length >= b.length to use O(min(n,m)) space
	if (m < n)
	{
		var c=a; a=b; b=c;
		var o=m; m=n; n=o;
	}

	var r = new Array();
	r[0] = new Array();
	for (var c = 0; c < n+1; c++)
		r[0][c] = c;

	for (var i = 1; i < m+1; i++)
	{
		r[i] = new Array();
		r[i][0] = i;

		for (var j = 1; j < n+1; j++)
		{
			cost = (a.charAt(i-1) == b.charAt(j-1))? 0: 1;
			r[i][j] = minimum (r[i-1][j]+1, r[i][j-1]+1, r[i-1][j-1]+cost);
		}
	}

	return r[r.length-1][r[r.length-1].length-1];
}