okapibm25 1.3.2 → 1.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/BM25.test.ts CHANGED
@@ -1,62 +1,109 @@
1
- import BM25, { getTermFrequency, getWordCount } from "./BM25";
2
-
3
- test("Irrelevant queries should return 0.", () => {
4
- const documents = ["fee", "fi", "fum"];
5
- const query = ["qwerty"];
6
- const results = BM25(documents, query, { k1: 1.3, b: 0.9 });
7
- results.forEach((result: number) => {
8
- expect(result).toBe(0);
1
+ import BM25, { BMDocument, getTermFrequency, getWordCount } from "./BM25";
2
+
3
+ describe("Bare bones functionality", () => {
4
+ test("Irrelevant queries should return 0.", () => {
5
+ const documents = ["fee", "fi", "fum"];
6
+ const query = ["qwerty"];
7
+ const results = BM25(documents, query, { k1: 1.3, b: 0.9 }) as number[];
8
+ results.forEach((result: number) => {
9
+ expect(result).toBe(0);
10
+ });
9
11
  });
10
- });
11
12
 
12
- test("Relevant queries should be greater than 0.", () => {
13
- const documents = ["fee", "feel", "I'm feeling lucky."];
14
- const query = ["fee"];
15
- const results = BM25(documents, query);
16
- results.forEach((result: number) => {
17
- expect(result).toBeGreaterThan(0);
13
+ test("Relevant queries should be greater than 0.", () => {
14
+ const documents = ["fee", "feel", "I'm feeling lucky."];
15
+ const query = ["fee"];
16
+ const results = BM25(documents, query) as number[];
17
+ results.forEach((result: number) => {
18
+ expect(result).toBeGreaterThan(0);
19
+ });
18
20
  });
19
- });
20
21
 
21
- test("Make sure word count is detected correctly", () => {
22
- const expectResults = [
23
- {
24
- corpus: "Pass the potatoes.",
25
- expect: 3,
26
- },
27
- { corpus: "pass.the.potatoes", expect: 3 },
28
- { corpus: "pass\nthe\npotatoes.", expect: 3 },
29
- ];
30
- expectResults.forEach((expectResult) => {
31
- const wordCount = getWordCount(expectResult.corpus);
32
- expect(wordCount).toBe(expectResult.expect);
22
+ test("Make sure word count is detected correctly", () => {
23
+ const expectResults = [
24
+ {
25
+ corpus: "Pass the potatoes.",
26
+ expect: 3,
27
+ },
28
+ { corpus: "pass.the.potatoes", expect: 3 },
29
+ { corpus: "pass\nthe\npotatoes.", expect: 3 },
30
+ ];
31
+ expectResults.forEach((expectResult) => {
32
+ const wordCount = getWordCount(expectResult.corpus);
33
+ expect(wordCount).toBe(expectResult.expect);
34
+ });
35
+ const emptyWordCount = getWordCount(null);
36
+ expect(emptyWordCount).toBe(0);
33
37
  });
34
- const emptyWordCount = getWordCount(null);
35
- expect(emptyWordCount).toBe(0);
36
- });
37
38
 
38
- test("Expect word frequency to be detected correctly", () => {
39
- // @ts-ignore
40
- const emptyWordFrequency = getTermFrequency("anything", null);
41
- expect(emptyWordFrequency).toBe(0);
42
- const expectResults = [
43
- {
44
- corpus: "Pass the pass.",
45
- term: "pass",
46
- expect: 1,
47
- },
48
- {
49
- corpus: "Pass the pass.",
50
- term: "Pass",
51
- expect: 1,
52
- },{
39
+ test("Expect word frequency to be detected correctly", () => {
40
+ // @ts-ignore
41
+ const emptyWordFrequency = getTermFrequency("anything", null);
42
+ expect(emptyWordFrequency).toBe(0);
43
+ const expectResults = [
44
+ {
45
+ corpus: "Pass the pass.",
46
+ term: "pass",
47
+ expect: 1,
48
+ },
49
+ {
50
+ corpus: "Pass the pass.",
51
+ term: "Pass",
52
+ expect: 1,
53
+ },
54
+ {
53
55
  corpus: "Pass.pass.pass.",
54
56
  term: "pass",
55
57
  expect: 2,
56
58
  },
57
- ];
58
- expectResults.forEach((expectResult) => {
59
- const result = getTermFrequency(expectResult.term, expectResult.corpus);
60
- expect(result).toBe(expectResult.expect);
59
+ ];
60
+ expectResults.forEach((expectResult) => {
61
+ const result = getTermFrequency(expectResult.term, expectResult.corpus);
62
+ expect(result).toBe(expectResult.expect);
63
+ });
64
+ });
65
+ });
66
+
67
+ describe("Testing fancy sorting mechanism.", () => {
68
+ test("Should sort in ascending order", () => {
69
+ const expectResults = new Map<number, string>();
70
+ expectResults.set(0, "The least relevant");
71
+ expectResults.set(1, "Medium relevant relevant");
72
+ expectResults.set(2, "The most relevant relevant relevant relevant");
73
+
74
+ const corpuses = Array.from(expectResults.values());
75
+ const results = BM25(
76
+ corpuses,
77
+ ["relevant"],
78
+ undefined,
79
+ (firstEl, secondEl) => {
80
+ return firstEl.score - secondEl.score;
81
+ }
82
+ ) as BMDocument[];
83
+ results.forEach((result, index) => {
84
+ const expectedDocument = expectResults.get(index);
85
+ expect(expectedDocument).toEqual(result.document);
86
+ });
87
+ });
88
+
89
+ test("Should sort in descending order", () => {
90
+ const expectResults = new Map<number, string>();
91
+ expectResults.set(2, "The least relevant");
92
+ expectResults.set(1, "Medium relevant relevant");
93
+ expectResults.set(0, "The most relevant relevant relevant relevant");
94
+
95
+ const corpuses = Array.from(expectResults.values());
96
+ const results = BM25(
97
+ corpuses,
98
+ ["relevant"],
99
+ undefined,
100
+ (firstEl, secondEl) => {
101
+ return secondEl.score - firstEl.score;
102
+ }
103
+ ) as BMDocument[];
104
+ results.forEach((result, index) => {
105
+ const expectedDocument = expectResults.get(index);
106
+ expect(expectedDocument).toEqual(result.document);
107
+ });
61
108
  });
62
109
  });
package/BM25.ts CHANGED
@@ -19,18 +19,39 @@ export const getIDF = (term: string, documents: string[]) => {
19
19
  );
20
20
  };
21
21
 
22
+ /** Represents a document; useful when sorting results.
23
+ */
24
+ export interface BMDocument {
25
+ /** The document is originally scoreed. */
26
+ document: string;
27
+ /** The score that the document recieves. */
28
+ score: number;
29
+ }
30
+
31
+ /** Constants that are free parameters used in BM25, specifically when generating inverse document frequency. */
32
+ export interface BMConstants {
33
+ /** Free parameter. Is 0.75 by default. */
34
+ b?: number;
35
+ /** Free parameter. Is 1.2 by default. Generally in range [1.2, 2.0] */
36
+ k1?: number;
37
+ }
38
+
39
+ /** If returns positive, the sorting results in secondEl coming before firstEl, else, firstEl comes before secondEL */
40
+ export type BMSorter = (firstEl: BMDocument, secondEl: BMDocument) => number;
41
+
22
42
  /** Implementation of Okapi BM25 algorithm.
23
- * @param documents: string[]. Collection of documents.
24
- * @param keywords: keywords within query.
25
- * @param constants: Contains free parameters k1 and b, which are free parameters,
26
- * where k1 is within [1.2, 2.0] and b = 0.75, in absence of advanced optimization.
27
- * In this implementation, k1 = 1.2.
43
+ * @param documents: Collection of documents.
44
+ * @param keywords: query terms.
45
+ * @param constants: Contains free parameters k1 and b. b=0.75 and k1=1.2 by default.
46
+ * @param sort: A function that allows you to sort queries by a given rule. If not provided, returns results corresponding to the original order.
47
+ * If this option is provided, the return type will not be an array of scores but an array of documents with their scores.
28
48
  */
29
49
  export default function BM25(
30
50
  documents: string[],
31
51
  keywords: string[],
32
- constants?: { b?: number; k1?: number }
33
- ): number[] {
52
+ constants?: BMConstants,
53
+ sorter?: BMSorter
54
+ ): number[] | BMDocument[] {
34
55
  const b = constants && constants.b ? constants.b : 0.75;
35
56
  const k1 = constants && constants.k1 ? constants.k1 : 1.2;
36
57
  const documentLengths = documents.map((document: string) =>
@@ -38,10 +59,15 @@ export default function BM25(
38
59
  );
39
60
  const averageDocumentLength =
40
61
  documentLengths.reduce((a, b) => a + b, 0) / documents.length;
62
+ const idfByKeyword = keywords.reduce((obj, keyword) => {
63
+ obj.set(keyword, getIDF(keyword, documents));
64
+ return obj;
65
+ }, new Map<string, number>());
66
+
41
67
  const scores = documents.map((document: string, index: number) => {
42
68
  const score = keywords
43
69
  .map((keyword: string) => {
44
- const inverseDocumentFrequency = getIDF(keyword, documents);
70
+ const inverseDocumentFrequency = idfByKeyword.get(keyword);
45
71
  const termFrequency = getTermFrequency(keyword, document);
46
72
  const documentLength = documentLengths[index];
47
73
  return (
@@ -51,7 +77,14 @@ export default function BM25(
51
77
  );
52
78
  })
53
79
  .reduce((a: number, b: number) => a + b, 0);
80
+ if (sorter) {
81
+ return { score, document} as BMDocument
82
+ }
54
83
  return score;
55
84
  });
56
- return scores;
85
+ // sort the results
86
+ if (sorter) {
87
+ return (scores as BMDocument[]).sort(sorter);
88
+ }
89
+ return scores as number[];
57
90
  }
package/README.md CHANGED
@@ -6,9 +6,10 @@
6
6
  ![Lines](https://img.shields.io/badge/lines-100%25-brightgreen.svg)
7
7
 
8
8
 
9
- There was no satisfactory implementation of the Okapi BM25 algorithm, so here is one to use. Just provide your documentations, query keywords, and (optionally) your weights (*b* and *k1*).
9
+ A strongly typed, well-tested implementation of the Okapi BM25 algorithm. Just provide your documents to search, query keywords, and (optionally) your weights (*b* and *k1*).
10
10
 
11
11
  ## Installation
12
+ Check out the [NPM package.](https://www.npmjs.com/package/okapibm25)
12
13
  ```
13
14
  npm install okapibm25 --save
14
15
  ```
@@ -24,9 +25,33 @@ const documents = [
24
25
  ];
25
26
  const query = ["keywords", "of", "your", "query."];
26
27
  // A numerical scoring will be returned.
27
- const result = BM25(documents, query, { k1: 1.3, b: 0.9 });
28
+ const result = BM25(documents, query, { k1: 1.3, b: 0.9 }) as number[];
28
29
  console.log(result);
29
30
 
30
31
  ```
32
+ ### Sorting
33
+ A recent update allows you to sort your documents. [This works very similar to JavaScript's Array.prototype.sort() function.](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort)
34
+
35
+ Here is an example of how to sort in descending order (by score).
36
+ ```
37
+ const results = BM25(
38
+ corpuses,
39
+ ["relevant"],
40
+ undefined,
41
+ (firstEl, secondEl) => {
42
+ return secondEl.score - firstEl.score;
43
+ }
44
+ ) as BMDocument[];
45
+ ```
46
+ I've purposely given a schema that lets you sort results by more than just score; you could also sort alphabetically (or by how many times the word 'unicorn' is mentioned, for all I care!) by comparing the documents as well. You can also even ignore scores while sorting!
47
+
48
+ *Important:* Note that enabling sorting changes the return type from `number[]` to `{ document: string; score: number; }[]`
49
+
50
+ ## What's this?
51
+ An implementation of OkapiBM25 (AKA BM25), a [bag-of-words](https://en.wikipedia.org/wiki/Bag-of-words_model) information retrieval algorithm. [Read up on it here](https://en.wikipedia.org/wiki/Okapi_BM25).
52
+
31
53
  ## License
32
54
  Under `license.md`
55
+
56
+ ## Contributing
57
+ Submit a Pull Request if you have a useful feature that you'd like to add. If you're too lazy or this isn't your area of expertise, open an issue and I'll get to it.
@@ -0,0 +1,350 @@
1
+
2
+ <!doctype html>
3
+ <html lang="en">
4
+
5
+ <head>
6
+ <title>Code coverage report for BM25.ts</title>
7
+ <meta charset="utf-8" />
8
+ <link rel="stylesheet" href="prettify.css" />
9
+ <link rel="stylesheet" href="base.css" />
10
+ <link rel="shortcut icon" type="image/x-icon" href="favicon.png" />
11
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
12
+ <style type='text/css'>
13
+ .coverage-summary .sorter {
14
+ background-image: url(sort-arrow-sprite.png);
15
+ }
16
+ </style>
17
+ </head>
18
+
19
+ <body>
20
+ <div class='wrapper'>
21
+ <div class='pad1'>
22
+ <h1><a href="index.html">All files</a> BM25.ts</h1>
23
+ <div class='clearfix'>
24
+
25
+ <div class='fl pad1y space-right2'>
26
+ <span class="strong">100% </span>
27
+ <span class="quiet">Statements</span>
28
+ <span class='fraction'>30/30</span>
29
+ </div>
30
+
31
+
32
+ <div class='fl pad1y space-right2'>
33
+ <span class="strong">100% </span>
34
+ <span class="quiet">Branches</span>
35
+ <span class='fraction'>20/20</span>
36
+ </div>
37
+
38
+
39
+ <div class='fl pad1y space-right2'>
40
+ <span class="strong">100% </span>
41
+ <span class="quiet">Functions</span>
42
+ <span class='fraction'>11/11</span>
43
+ </div>
44
+
45
+
46
+ <div class='fl pad1y space-right2'>
47
+ <span class="strong">100% </span>
48
+ <span class="quiet">Lines</span>
49
+ <span class='fraction'>29/29</span>
50
+ </div>
51
+
52
+
53
+ </div>
54
+ <p class="quiet">
55
+ Press <em>n</em> or <em>j</em> to go to the next uncovered block, <em>b</em>, <em>p</em> or <em>k</em> for the previous block.
56
+ </p>
57
+ </div>
58
+ <div class='status-line high'></div>
59
+ <pre><table class="coverage">
60
+ <tr><td class="line-count quiet"><a name='L1'></a><a href='#L1'>1</a>
61
+ <a name='L2'></a><a href='#L2'>2</a>
62
+ <a name='L3'></a><a href='#L3'>3</a>
63
+ <a name='L4'></a><a href='#L4'>4</a>
64
+ <a name='L5'></a><a href='#L5'>5</a>
65
+ <a name='L6'></a><a href='#L6'>6</a>
66
+ <a name='L7'></a><a href='#L7'>7</a>
67
+ <a name='L8'></a><a href='#L8'>8</a>
68
+ <a name='L9'></a><a href='#L9'>9</a>
69
+ <a name='L10'></a><a href='#L10'>10</a>
70
+ <a name='L11'></a><a href='#L11'>11</a>
71
+ <a name='L12'></a><a href='#L12'>12</a>
72
+ <a name='L13'></a><a href='#L13'>13</a>
73
+ <a name='L14'></a><a href='#L14'>14</a>
74
+ <a name='L15'></a><a href='#L15'>15</a>
75
+ <a name='L16'></a><a href='#L16'>16</a>
76
+ <a name='L17'></a><a href='#L17'>17</a>
77
+ <a name='L18'></a><a href='#L18'>18</a>
78
+ <a name='L19'></a><a href='#L19'>19</a>
79
+ <a name='L20'></a><a href='#L20'>20</a>
80
+ <a name='L21'></a><a href='#L21'>21</a>
81
+ <a name='L22'></a><a href='#L22'>22</a>
82
+ <a name='L23'></a><a href='#L23'>23</a>
83
+ <a name='L24'></a><a href='#L24'>24</a>
84
+ <a name='L25'></a><a href='#L25'>25</a>
85
+ <a name='L26'></a><a href='#L26'>26</a>
86
+ <a name='L27'></a><a href='#L27'>27</a>
87
+ <a name='L28'></a><a href='#L28'>28</a>
88
+ <a name='L29'></a><a href='#L29'>29</a>
89
+ <a name='L30'></a><a href='#L30'>30</a>
90
+ <a name='L31'></a><a href='#L31'>31</a>
91
+ <a name='L32'></a><a href='#L32'>32</a>
92
+ <a name='L33'></a><a href='#L33'>33</a>
93
+ <a name='L34'></a><a href='#L34'>34</a>
94
+ <a name='L35'></a><a href='#L35'>35</a>
95
+ <a name='L36'></a><a href='#L36'>36</a>
96
+ <a name='L37'></a><a href='#L37'>37</a>
97
+ <a name='L38'></a><a href='#L38'>38</a>
98
+ <a name='L39'></a><a href='#L39'>39</a>
99
+ <a name='L40'></a><a href='#L40'>40</a>
100
+ <a name='L41'></a><a href='#L41'>41</a>
101
+ <a name='L42'></a><a href='#L42'>42</a>
102
+ <a name='L43'></a><a href='#L43'>43</a>
103
+ <a name='L44'></a><a href='#L44'>44</a>
104
+ <a name='L45'></a><a href='#L45'>45</a>
105
+ <a name='L46'></a><a href='#L46'>46</a>
106
+ <a name='L47'></a><a href='#L47'>47</a>
107
+ <a name='L48'></a><a href='#L48'>48</a>
108
+ <a name='L49'></a><a href='#L49'>49</a>
109
+ <a name='L50'></a><a href='#L50'>50</a>
110
+ <a name='L51'></a><a href='#L51'>51</a>
111
+ <a name='L52'></a><a href='#L52'>52</a>
112
+ <a name='L53'></a><a href='#L53'>53</a>
113
+ <a name='L54'></a><a href='#L54'>54</a>
114
+ <a name='L55'></a><a href='#L55'>55</a>
115
+ <a name='L56'></a><a href='#L56'>56</a>
116
+ <a name='L57'></a><a href='#L57'>57</a>
117
+ <a name='L58'></a><a href='#L58'>58</a>
118
+ <a name='L59'></a><a href='#L59'>59</a>
119
+ <a name='L60'></a><a href='#L60'>60</a>
120
+ <a name='L61'></a><a href='#L61'>61</a>
121
+ <a name='L62'></a><a href='#L62'>62</a>
122
+ <a name='L63'></a><a href='#L63'>63</a>
123
+ <a name='L64'></a><a href='#L64'>64</a>
124
+ <a name='L65'></a><a href='#L65'>65</a>
125
+ <a name='L66'></a><a href='#L66'>66</a>
126
+ <a name='L67'></a><a href='#L67'>67</a>
127
+ <a name='L68'></a><a href='#L68'>68</a>
128
+ <a name='L69'></a><a href='#L69'>69</a>
129
+ <a name='L70'></a><a href='#L70'>70</a>
130
+ <a name='L71'></a><a href='#L71'>71</a>
131
+ <a name='L72'></a><a href='#L72'>72</a>
132
+ <a name='L73'></a><a href='#L73'>73</a>
133
+ <a name='L74'></a><a href='#L74'>74</a>
134
+ <a name='L75'></a><a href='#L75'>75</a>
135
+ <a name='L76'></a><a href='#L76'>76</a>
136
+ <a name='L77'></a><a href='#L77'>77</a>
137
+ <a name='L78'></a><a href='#L78'>78</a>
138
+ <a name='L79'></a><a href='#L79'>79</a>
139
+ <a name='L80'></a><a href='#L80'>80</a>
140
+ <a name='L81'></a><a href='#L81'>81</a>
141
+ <a name='L82'></a><a href='#L82'>82</a>
142
+ <a name='L83'></a><a href='#L83'>83</a>
143
+ <a name='L84'></a><a href='#L84'>84</a>
144
+ <a name='L85'></a><a href='#L85'>85</a>
145
+ <a name='L86'></a><a href='#L86'>86</a>
146
+ <a name='L87'></a><a href='#L87'>87</a>
147
+ <a name='L88'></a><a href='#L88'>88</a>
148
+ <a name='L89'></a><a href='#L89'>89</a>
149
+ <a name='L90'></a><a href='#L90'>90</a>
150
+ <a name='L91'></a><a href='#L91'>91</a></td><td class="line-coverage quiet"><span class="cline-any cline-neutral">&nbsp;</span>
151
+ <span class="cline-any cline-yes">1x</span>
152
+ <span class="cline-any cline-yes">16x</span>
153
+ <span class="cline-any cline-neutral">&nbsp;</span>
154
+ <span class="cline-any cline-neutral">&nbsp;</span>
155
+ <span class="cline-any cline-neutral">&nbsp;</span>
156
+ <span class="cline-any cline-yes">1x</span>
157
+ <span class="cline-any cline-yes">16x</span>
158
+ <span class="cline-any cline-neutral">&nbsp;</span>
159
+ <span class="cline-any cline-neutral">&nbsp;</span>
160
+ <span class="cline-any cline-neutral">&nbsp;</span>
161
+ <span class="cline-any cline-yes">1x</span>
162
+ <span class="cline-any cline-neutral">&nbsp;</span>
163
+ <span class="cline-any cline-yes">4x</span>
164
+ <span class="cline-any cline-yes">12x</span>
165
+ <span class="cline-any cline-neutral">&nbsp;</span>
166
+ <span class="cline-any cline-yes">4x</span>
167
+ <span class="cline-any cline-neutral">&nbsp;</span>
168
+ <span class="cline-any cline-neutral">&nbsp;</span>
169
+ <span class="cline-any cline-neutral">&nbsp;</span>
170
+ <span class="cline-any cline-neutral">&nbsp;</span>
171
+ <span class="cline-any cline-neutral">&nbsp;</span>
172
+ <span class="cline-any cline-neutral">&nbsp;</span>
173
+ <span class="cline-any cline-neutral">&nbsp;</span>
174
+ <span class="cline-any cline-neutral">&nbsp;</span>
175
+ <span class="cline-any cline-neutral">&nbsp;</span>
176
+ <span class="cline-any cline-neutral">&nbsp;</span>
177
+ <span class="cline-any cline-neutral">&nbsp;</span>
178
+ <span class="cline-any cline-neutral">&nbsp;</span>
179
+ <span class="cline-any cline-neutral">&nbsp;</span>
180
+ <span class="cline-any cline-neutral">&nbsp;</span>
181
+ <span class="cline-any cline-neutral">&nbsp;</span>
182
+ <span class="cline-any cline-neutral">&nbsp;</span>
183
+ <span class="cline-any cline-neutral">&nbsp;</span>
184
+ <span class="cline-any cline-neutral">&nbsp;</span>
185
+ <span class="cline-any cline-neutral">&nbsp;</span>
186
+ <span class="cline-any cline-neutral">&nbsp;</span>
187
+ <span class="cline-any cline-neutral">&nbsp;</span>
188
+ <span class="cline-any cline-neutral">&nbsp;</span>
189
+ <span class="cline-any cline-neutral">&nbsp;</span>
190
+ <span class="cline-any cline-neutral">&nbsp;</span>
191
+ <span class="cline-any cline-neutral">&nbsp;</span>
192
+ <span class="cline-any cline-neutral">&nbsp;</span>
193
+ <span class="cline-any cline-neutral">&nbsp;</span>
194
+ <span class="cline-any cline-neutral">&nbsp;</span>
195
+ <span class="cline-any cline-neutral">&nbsp;</span>
196
+ <span class="cline-any cline-neutral">&nbsp;</span>
197
+ <span class="cline-any cline-neutral">&nbsp;</span>
198
+ <span class="cline-any cline-neutral">&nbsp;</span>
199
+ <span class="cline-any cline-neutral">&nbsp;</span>
200
+ <span class="cline-any cline-neutral">&nbsp;</span>
201
+ <span class="cline-any cline-neutral">&nbsp;</span>
202
+ <span class="cline-any cline-neutral">&nbsp;</span>
203
+ <span class="cline-any cline-neutral">&nbsp;</span>
204
+ <span class="cline-any cline-yes">4x</span>
205
+ <span class="cline-any cline-yes">4x</span>
206
+ <span class="cline-any cline-yes">4x</span>
207
+ <span class="cline-any cline-yes">12x</span>
208
+ <span class="cline-any cline-neutral">&nbsp;</span>
209
+ <span class="cline-any cline-neutral">&nbsp;</span>
210
+ <span class="cline-any cline-yes">12x</span>
211
+ <span class="cline-any cline-yes">4x</span>
212
+ <span class="cline-any cline-yes">4x</span>
213
+ <span class="cline-any cline-yes">4x</span>
214
+ <span class="cline-any cline-neutral">&nbsp;</span>
215
+ <span class="cline-any cline-neutral">&nbsp;</span>
216
+ <span class="cline-any cline-yes">4x</span>
217
+ <span class="cline-any cline-yes">12x</span>
218
+ <span class="cline-any cline-neutral">&nbsp;</span>
219
+ <span class="cline-any cline-yes">12x</span>
220
+ <span class="cline-any cline-yes">12x</span>
221
+ <span class="cline-any cline-yes">12x</span>
222
+ <span class="cline-any cline-yes">12x</span>
223
+ <span class="cline-any cline-neutral">&nbsp;</span>
224
+ <span class="cline-any cline-neutral">&nbsp;</span>
225
+ <span class="cline-any cline-neutral">&nbsp;</span>
226
+ <span class="cline-any cline-neutral">&nbsp;</span>
227
+ <span class="cline-any cline-neutral">&nbsp;</span>
228
+ <span class="cline-any cline-yes">12x</span>
229
+ <span class="cline-any cline-yes">12x</span>
230
+ <span class="cline-any cline-yes">6x</span>
231
+ <span class="cline-any cline-neutral">&nbsp;</span>
232
+ <span class="cline-any cline-yes">6x</span>
233
+ <span class="cline-any cline-neutral">&nbsp;</span>
234
+ <span class="cline-any cline-neutral">&nbsp;</span>
235
+ <span class="cline-any cline-yes">4x</span>
236
+ <span class="cline-any cline-yes">2x</span>
237
+ <span class="cline-any cline-neutral">&nbsp;</span>
238
+ <span class="cline-any cline-yes">2x</span>
239
+ <span class="cline-any cline-neutral">&nbsp;</span>
240
+ <span class="cline-any cline-neutral">&nbsp;</span></td><td class="text"><pre class="prettyprint lang-js">/** Gets word count. */
241
+ export const getWordCount = (corpus: string) =&gt; {
242
+ return ((corpus || "").match(/\w+/g) || []).length;
243
+ };
244
+ &nbsp;
245
+ /** Number of occurences of a word in a string. */
246
+ export const getTermFrequency = (term: string, corpus: string) =&gt; {
247
+ return ((corpus || "").match(new RegExp(term, "g")) || []).length;
248
+ };
249
+ &nbsp;
250
+ /** Inverse document frequency. */
251
+ export const getIDF = (term: string, documents: string[]) =&gt; {
252
+ // Number of relevant documents.
253
+ const relevantDocuments = documents.filter((document: string) =&gt;
254
+ document.includes(term)
255
+ ).length;
256
+ return Math.log(
257
+ (documents.length - relevantDocuments + 0.5) / (relevantDocuments + 0.5) + 1
258
+ );
259
+ };
260
+ &nbsp;
261
+ /** Represents a document; useful when sorting results.
262
+ */
263
+ export interface BMDocument {
264
+ /** The document is originally scoreed. */
265
+ document: string;
266
+ /** The score that the document recieves. */
267
+ score: number;
268
+ }
269
+ &nbsp;
270
+ /** Constants that are free parameters used in BM25, specifically when generating inverse document frequency. */
271
+ export interface BMConstants {
272
+ /** Free parameter. Is 0.75 by default. */
273
+ b?: number;
274
+ /** Free parameter. Is 1.2 by default. Generally in range [1.2, 2.0] */
275
+ k1?: number;
276
+ }
277
+ &nbsp;
278
+ /** If returns positive, the sorting results in secondEl coming before firstEl, else, firstEl comes before secondEL */
279
+ export type BMSorter = (firstEl: BMDocument, secondEl: BMDocument) =&gt; number;
280
+ &nbsp;
281
+ /** Implementation of Okapi BM25 algorithm.
282
+ * @param documents: Collection of documents.
283
+ * @param keywords: query terms.
284
+ * @param constants: Contains free parameters k1 and b. b=0.75 and k1=1.2 by default.
285
+ * @param sort: A function that allows you to sort queries by a given rule. If not provided, returns results corresponding to the original order.
286
+ * If this option is provided, the return type will not be an array of scores but an array of documents with their scores.
287
+ */
288
+ export default function BM25(
289
+ documents: string[],
290
+ keywords: string[],
291
+ constants?: BMConstants,
292
+ sorter?: BMSorter
293
+ ): number[] | BMDocument[] {
294
+ const b = constants &amp;&amp; constants.b ? constants.b : 0.75;
295
+ const k1 = constants &amp;&amp; constants.k1 ? constants.k1 : 1.2;
296
+ const documentLengths = documents.map((document: string) =&gt;
297
+ getWordCount(document)
298
+ );
299
+ const averageDocumentLength =
300
+ documentLengths.reduce((a, b) =&gt; a + b, 0) / documents.length;
301
+ const idfByKeyword = keywords.reduce((obj, keyword) =&gt; {
302
+ obj.set(keyword, getIDF(keyword, documents));
303
+ return obj;
304
+ }, new Map&lt;string, number&gt;());
305
+ &nbsp;
306
+ const scores = documents.map((document: string, index: number) =&gt; {
307
+ const score = keywords
308
+ .map((keyword: string) =&gt; {
309
+ const inverseDocumentFrequency = idfByKeyword.get(keyword);
310
+ const termFrequency = getTermFrequency(keyword, document);
311
+ const documentLength = documentLengths[index];
312
+ return (
313
+ (inverseDocumentFrequency * (termFrequency * (k1 + 1))) /
314
+ (termFrequency +
315
+ k1 * (1 - b + (b * documentLength) / averageDocumentLength))
316
+ );
317
+ })
318
+ .reduce((a: number, b: number) =&gt; a + b, 0);
319
+ if (sorter) {
320
+ return { score, document} as BMDocument
321
+ }
322
+ return score;
323
+ });
324
+ // sort the results
325
+ if (sorter) {
326
+ return (scores as BMDocument[]).sort(sorter);
327
+ }
328
+ return scores as number[];
329
+ }
330
+ &nbsp;</pre></td></tr></table></pre>
331
+
332
+ <div class='push'></div><!-- for sticky footer -->
333
+ </div><!-- /wrapper -->
334
+ <div class='footer quiet pad2 space-top1 center small'>
335
+ Code coverage generated by
336
+ <a href="https://istanbul.js.org/" target="_blank">istanbul</a>
337
+ at Mon Sep 09 2024 00:56:14 GMT-0700 (Pacific Daylight Time)
338
+ </div>
339
+ </div>
340
+ <script src="prettify.js"></script>
341
+ <script>
342
+ window.onload = function () {
343
+ prettyPrint();
344
+ };
345
+ </script>
346
+ <script src="sorter.js"></script>
347
+ <script src="block-navigation.js"></script>
348
+ </body>
349
+ </html>
350
+