Skip to content

Instantly share code, notes, and snippets.

@Sam-Gram
Last active August 24, 2018 20:53
Show Gist options
  • Save Sam-Gram/78cca4d44923c068c6342f6c15722d2b to your computer and use it in GitHub Desktop.
Save Sam-Gram/78cca4d44923c068c6342f6c15722d2b to your computer and use it in GitHub Desktop.
String distance in JavaScript
/**
GLWT(Good Luck With That) Public License
Copyright (c) Everyone, except Author
The author has absolutely no clue what the code in this project does.
It might just work or not, there is no third option.
Everyone is permitted to copy, distribute, modify, merge, sell, publish,
sublicense or whatever they want with this software but at their OWN RISK.
GOOD LUCK WITH THAT PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION, AND MODIFICATION
0. You just DO WHATEVER YOU WANT TO as long as you NEVER LEAVE A
TRACE TO TRACK THE AUTHOR of the original product to blame for or hold
responsible.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Good luck.
*/
function stringDistance(a,b) {
let editTracker = (new Array(a.length+1)).fill(0).map(_=>(new Array(b.length+1)).fill(0))
for (let i = 0; i <= a.length; i++) {
for (let j = 0; j <= b.length; j++) {
if (i === 0) {
editTracker[i][j] = j
} else if (j === 0) {
editTracker[i][j] = i
} else if (a[i-1] === b[j-1]) {
editTracker[i][j] = editTracker[i-1][j-1]
} else {
editTracker[i][j] = 1 +
Math.min(editTracker[i][j-1],
editTracker[i-1][j],
editTracker[i-1][j-1])
}
}
}
return editTracker[a.length][b.length]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment