Bug 1885565 - Part 1: Add mozac_ic_avatar_circle_24 to ui-icons r=android-reviewers...
[gecko.git] / toolkit / modules / NLP.sys.mjs
blobe2de0f245c56787f4963c50d9ca43f6b4cd1caf3
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/. */
5 /**
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.
8  *
9  * At least, that's the goal. Eventually. Right now, the find toolbar only really
10  * needs the Levenshtein distance algorithm.
11  */
12 export var NLP = {
13   /**
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
17    * License: MIT.
18    *
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
24    * @return {Number}
25    */
26   levenshtein(word1 = "", word2 = "", costIns = 1, costRep = 1, costDel = 1) {
27     if (word1 === word2) {
28       return 0;
29     }
31     let l1 = word1.length;
32     let l2 = word2.length;
33     if (!l1) {
34       return l2 * costIns;
35     }
36     if (!l2) {
37       return l1 * costDel;
38     }
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;
47     }
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;
56         if (c1 < c0) {
57           c0 = c1;
58         }
60         c2 = p2[i2] + costIns;
62         if (c2 < c0) {
63           c0 = c2;
64         }
66         p2[i2 + 1] = c0;
67       }
69       tmp = p1;
70       p1 = p2;
71       p2 = tmp;
72     }
74     c0 = p1[l2];
76     return c0;
77   },