URL: https://gist.github.com/812443

I needed a very basic spell correction string matcher in my current NodeJS project so I wrote a simple class called EditDistanceMatcher that compares a string against another string and matches if it's 1 edit distance away. With it you can do things like Google search's "Did you mean: poop?" when you search for pop.

Note, this code doesn't check popularity of correct words (e.g. "pop" might appear much more often than "poop" so it'll suggest "pop" if you enter "poup"). Anyway this simple snippet from the unit tests will reveal how it works:


     /* The match() method */
     var edm = new EditDistanceMatcher(["peter"]);
     // edm.match returns an array and remember,
     // in javascript ['peter'] == ['peter'] => false
     test.equal(edm.match("petter").length, 1);
     test.equal(edm.match("petter")[0], 'peter');
     test.equal(edm.match("junk").length, 0);

     /* the is_matched() method */
     var edm = new EditDistanceMatcher(["peter"]);
     test.equal(typeof edm.is_matched('petter'), 'boolean');
     test.equal(typeof edm.is_matched('junk'), 'boolean');
     test.ok(edm.is_matched("petter"));
     test.ok(!edm.is_matched("junk"));

The most basic use case is if you have a quiz and you want to accept some spelling mistakes. "What's the capital of Sweden?; STOKHOLM; Correct!"

For the unlazy this NodeJS code can very easily be used in a browser by simply removing the exports stuff.

edit_distance.js

tests/test_edit_distance.js

Note! I wrote this in an airport lounge so I'm sure it can be improved lots more.

Your email will never ever be published.

Previous:
DoneCal on MumbaiMirror February 3, 2011 DoneCal
Next:
DoneCal homepage now able to do 10,000 requests/second February 13, 2011 DoneCal
Related by category:
You don't need a context or state manager for TanStack Query in scattered React components January 2, 2026 JavaScript
How to handle success and failure in @tanstack/react-query useQuery hook September 16, 2024 JavaScript
gg2 has a web page now January 5, 2026 JavaScript
gg2 branches got 50% faster by a Promise.all February 16, 2026 JavaScript
Related by keyword:
NodeJS fs walk() or glob or fast-glob August 31, 2019 JavaScript
Replace an item in an array, by number, without mutation in JavaScript (ES6) August 23, 2018 JavaScript
How's My WiFi? December 8, 2017 Node, JavaScript, macOS
To assert or assertEqual in Python unit testing February 14, 2009 Python