1 /* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6 * NLP, which stands for Natural Language Processing, is a module that provides
7 * an entry point to various methods to interface with human language.
9 * At least, that's the goal. Eventually. Right now, the find toolbar only really
10 * needs the Levenshtein distance algorithm.
14 * Calculate the Levenshtein distance between two words.
15 * The implementation of this method was heavily inspired by
16 * http://locutus.io/php/strings/levenshtein/index.html
19 * @param {String} word1 Word to compare against
20 * @param {String} word2 Word that may be different
21 * @param {Number} costIns The cost to insert a character
22 * @param {Number} costRep The cost to replace a character
23 * @param {Number} costDel The cost to delete a character
26 levenshtein(word1 = "", word2 = "", costIns = 1, costRep = 1, costDel = 1) {
27 if (word1 === word2) {
31 let l1 = word1.length;
32 let l2 = word2.length;
40 let p1 = new Array(l2 + 1);
41 let p2 = new Array(l2 + 1);
43 let i1, i2, c0, c1, c2, tmp;
45 for (i2 = 0; i2 <= l2; i2++) {
46 p1[i2] = i2 * costIns;
49 for (i1 = 0; i1 < l1; i1++) {
50 p2[0] = p1[0] + costDel;
52 for (i2 = 0; i2 < l2; i2++) {
53 c0 = p1[i2] + (word1[i1] === word2[i2] ? 0 : costRep);
54 c1 = p1[i2 + 1] + costDel;
60 c2 = p2[i2] + costIns;