levenshtein.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. /*
  2. Copyright (c) 2011 Andrei Mackenzie
  3. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
  4. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
  5. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS 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.
  6. */
  7. // levenshtein distance algorithm, pulled from Andrei Mackenzie's MIT licensed.
  8. // gist, which can be found here: https://gist.github.com/andrei-m/982927
  9. 'use strict'
  10. // Compute the edit distance between the two given strings
  11. module.exports = function levenshtein (a, b) {
  12. if (a.length === 0) return b.length
  13. if (b.length === 0) return a.length
  14. const matrix = []
  15. // increment along the first column of each row
  16. let i
  17. for (i = 0; i <= b.length; i++) {
  18. matrix[i] = [i]
  19. }
  20. // increment each column in the first row
  21. let j
  22. for (j = 0; j <= a.length; j++) {
  23. matrix[0][j] = j
  24. }
  25. // Fill in the rest of the matrix
  26. for (i = 1; i <= b.length; i++) {
  27. for (j = 1; j <= a.length; j++) {
  28. if (b.charAt(i - 1) === a.charAt(j - 1)) {
  29. matrix[i][j] = matrix[i - 1][j - 1]
  30. } else {
  31. matrix[i][j] = Math.min(matrix[i - 1][j - 1] + 1, // substitution
  32. Math.min(matrix[i][j - 1] + 1, // insertion
  33. matrix[i - 1][j] + 1)) // deletion
  34. }
  35. }
  36. }
  37. return matrix[b.length][a.length]
  38. }