similarly 0.0.0-stage → 1.0.0

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/CHANGELOG.md ADDED
@@ -0,0 +1,15 @@
1
+ # Changelog
2
+
3
+ All notable changes to this package are documented here. This project follows [Semantic Versioning](https://semver.org/).
4
+
5
+ ## 1.0.0 - 2026-11-28
6
+
7
+ First release.
8
+
9
+ - Drop-in for the deprecated string-similarity 4: `compareTwoStrings()` and `findBestMatch()` give the same results, return shapes and errors, checked against the real package on more than 1,000 inputs. `require('similarly')` and the default export return `{ compareTwoStrings, findBestMatch }`.
10
+ - `similarity(a, b, options)` with nine algorithms: `'dice'` (default), `'levenshtein'`, `'damerauLevenshtein'` (optimal string alignment), `'jaro'`, `'jaroWinkler'`, `'jaccard'`, `'cosine'`, `'lcs'` and `'hamming'`. Every score is from 0 to 1.
11
+ - `distance(a, b, options)` for Levenshtein, Damerau-Levenshtein, Hamming and LCS edit distances. Levenshtein is bit-parallel (32 characters per step), and `maxDistance` stops early.
12
+ - `rank()` and `bestMatch()` for lists of strings or objects, with `key`, `threshold`, `limit` and `algorithm`. Results are `{ item, target, rating, index }`, sorted and stable.
13
+ - Text options: `caseSensitive` (default `false`), `ignoreWhitespace`, `ignorePunctuation`, `ignoreAccents` (NFKD, keeps Indian vowel signs) and `graphemes` (default `true`, uses `Intl.Segmenter`, with a fallback). Emoji, Hindi and Tamil are not split into broken pieces.
14
+ - `normalize()` and `graphemes()` helpers, `algorithms` list, and TypeScript types (`Rating` and `BestMatch` match `@types/string-similarity`).
15
+ - ESM + CommonJS, zero dependencies. Node.js 20+, browsers, Deno, Bun and edge runtimes.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 CK Giri
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,476 @@
1
- # Temporary Holding Version
1
+ # similarly
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Compare how similar two strings are and find the best match in a list. A drop-in replacement for the deprecated `string-similarity`, with TypeScript types and more algorithms.
4
+
5
+ [![npm version](https://img.shields.io/npm/v/similarly.svg)](https://www.npmjs.com/package/similarly) [![bundle size](https://img.shields.io/bundlephobia/minzip/similarly)](https://bundlephobia.com/package/similarly) [![license](https://img.shields.io/npm/l/similarly.svg)](LICENSE)
6
+
7
+ `similarly` gives you a **similarity score** for two strings: a number from 0 to 1. `0` means they have nothing in common. `1` means they are the same. You can use it to:
8
+
9
+ 1. **Compare two strings**, for example to catch a typo in a city name.
10
+ 2. **Find the best match** for a search word in a list of strings or objects.
11
+ 3. **Rank a list** from most to least similar.
12
+
13
+ The package `string-similarity` (about 3 million downloads a week) is deprecated and has not had a release since 2021. `similarly` has the same two functions with the same results, so moving over is a one-line change.
14
+
15
+ ## Features
16
+
17
+ - **Drop-in for string-similarity.** `compareTwoStrings()` and `findBestMatch()` give the same numbers, the same objects and the same errors as string-similarity 4. Tested on more than 1,000 inputs against the real package.
18
+ - **Nine algorithms.** Dice (the default), Levenshtein, Damerau-Levenshtein, Jaro, Jaro-Winkler, Jaccard, cosine, longest common subsequence and Hamming.
19
+ - **Fast edit distances.** `distance('kitten', 'sitting')` returns `3`. Levenshtein compares 32 characters at a time, and a `maxDistance` option stops early, for fast "is it close?" checks.
20
+ - **Rank and search.** `rank()` and `bestMatch()` work on strings or objects, with `threshold`, `limit` and a `key` to pick the field.
21
+ - **Ignore what does not matter.** Upper and lower case, accents (`café` and `cafe`), punctuation and spaces.
22
+ - **Emoji and Indian languages.** Strings are split into the characters a reader sees, so `👍🏽` and the Hindi syllable `स्ते` each count as one character.
23
+ - **TypeScript types included.** No other packages needed. About 4.5 KB compressed.
24
+ - **Works everywhere.** Node.js 20+, browsers, Deno, Bun and edge runtimes. `import` and `require` both work.
25
+
26
+ ## Installation
27
+
28
+ If your project uses npm:
29
+
30
+ ```sh
31
+ npm install similarly
32
+ ```
33
+
34
+ Or with another package manager:
35
+
36
+ ```sh
37
+ pnpm add similarly
38
+ yarn add similarly
39
+ bun add similarly
40
+ ```
41
+
42
+ ## Quick start
43
+
44
+ ### Get started in 3 steps
45
+
46
+ **Step 1. Install the package** (see [Installation](#installation)).
47
+
48
+ **Step 2. Compare two strings.**
49
+
50
+ ```js
51
+ import { similarity } from 'similarly'
52
+
53
+ similarity('Healed', 'sealed') // => 0.8
54
+ similarity('Healed', 'healed') // => 1 (case is ignored by default)
55
+ ```
56
+
57
+ **Step 3. Find the best match in a list.**
58
+
59
+ ```js
60
+ import { bestMatch } from 'similarly'
61
+
62
+ bestMatch('appel', ['apple', 'maple', 'banana'])
63
+ // => { item: 'apple', target: 'apple', rating: 0.5, index: 0 }
64
+ ```
65
+
66
+ That's it. Already using string-similarity? Change one line and keep your code. See [Migrating from string-similarity](#migrating-from-string-similarity).
67
+
68
+ ## Table of contents
69
+
70
+ - [Usage](#usage)
71
+ - [Compare two strings](#compare-two-strings)
72
+ - [Find the best match](#find-the-best-match)
73
+ - [Rank a list](#rank-a-list)
74
+ - [Search objects by a field](#search-objects-by-a-field)
75
+ - [Choose an algorithm](#choose-an-algorithm)
76
+ - [Measure the edit distance](#measure-the-edit-distance)
77
+ - [Ignore case, accents and punctuation](#ignore-case-accents-and-punctuation)
78
+ - [Work with emoji and Indian languages](#work-with-emoji-and-indian-languages)
79
+ - [API](#api)
80
+ - [Comparison](#comparison)
81
+ - [Migrating from string-similarity](#migrating-from-string-similarity)
82
+ - [Notes and limitations](#notes-and-limitations)
83
+ - [Requirements](#requirements)
84
+ - [Credits](#credits)
85
+ - [License](#license)
86
+
87
+ ## Usage
88
+
89
+ ### Compare two strings
90
+
91
+ `similarity()` returns a score from 0 to 1. By default it uses the **Dice coefficient**, the same method as string-similarity: it splits each string into pairs of neighbouring characters (`he`, `ea`, `al`, ...) and counts how many pairs the two strings share.
92
+
93
+ ```js
94
+ import { similarity } from 'similarly'
95
+
96
+ similarity('Healed', 'sealed') // => 0.8
97
+ similarity('Asha Verma', 'Verma Asha') // => 0.8888888888888888
98
+ similarity('New Delhi', 'Mumbai') // => 0
99
+ ```
100
+
101
+ By default `similarity()` ignores upper and lower case. It does not ignore spaces, accents or punctuation unless you ask (see [Ignore case, accents and punctuation](#ignore-case-accents-and-punctuation)).
102
+
103
+ If you need the exact string-similarity behaviour (case-sensitive, spaces removed), use `compareTwoStrings()`:
104
+
105
+ ```js
106
+ import { compareTwoStrings } from 'similarly'
107
+
108
+ compareTwoStrings('healed', 'sealed') // => 0.8
109
+ ```
110
+
111
+ ### Find the best match
112
+
113
+ `bestMatch()` returns the most similar item, or `undefined` if the list is empty or nothing reaches the `threshold`.
114
+
115
+ ```js
116
+ import { bestMatch } from 'similarly'
117
+
118
+ bestMatch('appel', ['apple', 'maple', 'banana'])
119
+ // => { item: 'apple', target: 'apple', rating: 0.5, index: 0 }
120
+
121
+ bestMatch('appel', ['apple', 'maple', 'banana'], { threshold: 0.6 })
122
+ // => undefined
123
+ ```
124
+
125
+ Each result has four fields:
126
+
127
+ - `item`: the entry from your list.
128
+ - `target`: the text that was compared.
129
+ - `rating`: the similarity score.
130
+ - `index`: the position in your list.
131
+
132
+ When two items have the same rating, the first one wins.
133
+
134
+ ### Rank a list
135
+
136
+ `rank()` scores every item and returns them from most to least similar. Items with the same rating stay in their original order.
137
+
138
+ ```js
139
+ import { rank } from 'similarly'
140
+
141
+ rank('appel', ['apple', 'maple', 'apply', 'banana'], { limit: 2 })
142
+ // => [
143
+ // { item: 'apple', target: 'apple', rating: 0.5, index: 0 },
144
+ // { item: 'apply', target: 'apply', rating: 0.5, index: 2 },
145
+ // ]
146
+ ```
147
+
148
+ - `limit` keeps only the top results.
149
+ - `threshold` drops results with a lower rating. `{ threshold: 0.3 }` keeps ratings of 0.3 and above.
150
+
151
+ ### Search objects by a field
152
+
153
+ Use `key` to say which text to compare. It can be a property name, or a function that returns the text. `item` in the result is your whole object.
154
+
155
+ ```js
156
+ import { bestMatch, rank } from 'similarly'
157
+
158
+ const people = [
159
+ { id: 1, name: 'Asha Verma', city: 'Pune' },
160
+ { id: 2, name: 'Ravi Menon', city: 'Kochi' },
161
+ { id: 3, name: 'CK', city: 'Chennai' },
162
+ ]
163
+
164
+ bestMatch('asha varma', people, { key: 'name' })
165
+ // => { item: { id: 1, name: 'Asha Verma', city: 'Pune' }, target: 'Asha Verma', rating: 0.7777777777777778, index: 0 }
166
+
167
+ rank('ravi kochi', people, { key: (p) => `${p.name} ${p.city}`, limit: 1 })
168
+ // => [{ item: { id: 2, ... }, target: 'Ravi Menon Kochi', rating: 0.75, index: 1 }]
169
+ ```
170
+
171
+ Items where the key gives `null` or `undefined` are skipped. Any other value that is not a string throws a `TypeError`.
172
+
173
+ ### Choose an algorithm
174
+
175
+ Pass `algorithm` to `similarity()`, `rank()` or `bestMatch()`. Every algorithm returns a score from 0 to 1.
176
+
177
+ ```js
178
+ import { similarity } from 'similarly'
179
+
180
+ similarity('MARTHA', 'MARHTA', { algorithm: 'jaroWinkler' }) // => 0.9611111111111111
181
+ similarity('kitten', 'sitting', { algorithm: 'levenshtein' }) // => 0.5714285714285714
182
+ ```
183
+
184
+ A few terms first:
185
+
186
+ - **Edit distance**: the number of single-character changes (insert, delete or replace) that turn one string into the other.
187
+ - **Levenshtein**: the most common edit distance. `kitten` to `sitting` takes 3 changes.
188
+ - **n-gram**: a group of `n` neighbouring characters. The 2-grams (bigrams) of `night` are `ni`, `ig`, `gh` and `ht`.
189
+ - **Jaro-Winkler**: counts characters that match and are close to each other, then adds a bonus when the strings start the same way. It was made for comparing names.
190
+
191
+ #### Which algorithm should I use?
192
+
193
+ | You want to | Use | Why |
194
+ |---|---|---|
195
+ | Replace string-similarity, or compare general text | `'dice'` (default) | Fast. Word order matters little. |
196
+ | Catch typos in short words | `'levenshtein'` | Counts the edits. Easy to explain. |
197
+ | Catch typos where two letters are swapped (`teh`, `the`) | `'damerauLevenshtein'` | A swap counts as one edit, not two. |
198
+ | Match names of people or places | `'jaroWinkler'` | Gives weight to the start of the string. |
199
+ | Compare sets of n-grams in a different way | `'jaccard'` or `'cosine'` | Common in search and data cleaning. |
200
+ | Compare long texts where characters may be inserted | `'lcs'` | Longest common subsequence: characters in the same order, gaps allowed. |
201
+ | Compare codes of the same length (PIN, hash) | `'hamming'` | Counts positions that differ. |
202
+
203
+ Word order is the biggest difference between them. Dice still sees the shared pairs when words are swapped. Levenshtein does not:
204
+
205
+ ```js
206
+ similarity('Asha Verma', 'Verma Asha') // => 0.8888888888888888
207
+ similarity('Asha Verma', 'Verma Asha', { algorithm: 'levenshtein' }) // => 0.19999999999999996
208
+ ```
209
+
210
+ ### Measure the edit distance
211
+
212
+ `distance()` returns a whole number of edits instead of a score.
213
+
214
+ ```js
215
+ import { distance } from 'similarly'
216
+
217
+ distance('kitten', 'sitting') // => 3
218
+ distance('teh', 'the') // => 2
219
+ distance('teh', 'the', { algorithm: 'damerauLevenshtein' }) // => 1
220
+ distance('karolin', 'kathrin', { algorithm: 'hamming' }) // => 3
221
+ ```
222
+
223
+ When you only care whether two strings are close, set `maxDistance`. The search stops as soon as the distance is bigger, and returns `maxDistance + 1`:
224
+
225
+ ```js
226
+ distance('color', 'colour', { maxDistance: 2 }) // => 1
227
+ distance('color', 'column', { maxDistance: 2 }) // => 3 (more than 2)
228
+ ```
229
+
230
+ ### Ignore case, accents and punctuation
231
+
232
+ All functions except `compareTwoStrings()` and `findBestMatch()` take these options:
233
+
234
+ ```js
235
+ import { similarity, normalize } from 'similarly'
236
+
237
+ similarity('Crème Brûlée', 'creme brulee') // => 0.45454545454545453
238
+ similarity('Crème Brûlée', 'creme brulee', { ignoreAccents: true }) // => 1
239
+
240
+ similarity("Rock 'n' Roll", 'rock n roll', { ignorePunctuation: true }) // => 1
241
+ similarity('New Delhi', 'NewDelhi', { ignoreWhitespace: true }) // => 1
242
+
243
+ // See the text that is compared:
244
+ normalize('Crème Brûlée!', { ignoreAccents: true, ignorePunctuation: true }) // => 'creme brulee'
245
+ ```
246
+
247
+ | Option | Default | What it does |
248
+ |---|---|---|
249
+ | `caseSensitive` | `false` | `false` ignores upper and lower case. |
250
+ | `ignoreWhitespace` | `false` | Removes spaces, tabs and line breaks. |
251
+ | `ignorePunctuation` | `false` | Removes punctuation such as `. , ! ? - ' "` and the Devanagari danda `।`. Keeps symbols and emoji. |
252
+ | `ignoreAccents` | `false` | Removes accent marks: `é` becomes `e`. Vowel signs in Indian scripts are kept. |
253
+ | `graphemes` | `true` | Splits text into the characters a reader sees. See the next section. |
254
+
255
+ Text is also put into one standard Unicode form (NFC) first, so `é` typed as one character and `é` typed as `e` plus an accent are the same.
256
+
257
+ ### Work with emoji and Indian languages
258
+
259
+ Many characters are stored as more than one JavaScript "character" (UTF-16 code unit). An emoji with a skin tone is four. The Hindi syllable `स्ते` is four. Most string libraries count these pieces, and can split an emoji in half.
260
+
261
+ `similarly` splits text into **graphemes**, the characters a reader sees, using `Intl.Segmenter`:
262
+
263
+ ```js
264
+ import { distance, graphemes, bestMatch } from 'similarly'
265
+
266
+ graphemes('नमस्ते 👍🏽') // => ['न', 'म', 'स्ते', ' ', '👍🏽']
267
+
268
+ distance('👍', '👍🏽') // => 1 (one emoji changed)
269
+ distance('👍', '👍🏽', { graphemes: false }) // => 2 (two code units added)
270
+
271
+ distance('नमस्ते', 'नमस्कार') // => 2
272
+ distance('வணக்கம்', 'வணக்கம') // => 1
273
+
274
+ bestMatch('சென்னை', ['மதுரை', 'சென்னை', 'கோவை']).item // => 'சென்னை'
275
+ ```
276
+
277
+ Set `graphemes: false` to compare UTF-16 code units, like string-similarity. It is a little faster, and it gives finer scores when only a vowel sign inside one syllable changes.
278
+
279
+ ## API
280
+
281
+ ### similarity(a, b, options?)
282
+
283
+ ```ts
284
+ function similarity(a: string, b: string, options?: SimilarityOptions): number
285
+ ```
286
+
287
+ Returns a similarity score from 0 to 1. `1` means the strings are the same after the options are applied. Throws a `TypeError` if `a` or `b` is not a string.
288
+
289
+ | Option | Type | Default | What it does |
290
+ |---|---|---|---|
291
+ | `algorithm` | `Algorithm` | `'dice'` | `'dice'`, `'levenshtein'`, `'damerauLevenshtein'`, `'jaro'`, `'jaroWinkler'`, `'jaccard'`, `'cosine'`, `'lcs'` or `'hamming'`. |
292
+ | `n` | `number` | `2` | n-gram size for `'dice'`, `'jaccard'` and `'cosine'`. |
293
+ | `prefixScale` | `number` | `0.1` | Jaro-Winkler: bonus for each shared starting character. |
294
+ | `maxPrefix` | `number` | `4` | Jaro-Winkler: how many starting characters can count. |
295
+ | `boostThreshold` | `number` | `0.7` | Jaro-Winkler: add the bonus only when the Jaro score is above this. `0` always adds it. |
296
+ | `caseSensitive`, `ignoreWhitespace`, `ignorePunctuation`, `ignoreAccents`, `graphemes` | `boolean` | see [the table above](#ignore-case-accents-and-punctuation) | Change the text before comparing. |
297
+
298
+ How each algorithm turns into a score:
299
+
300
+ | Algorithm | Score |
301
+ |---|---|
302
+ | `'dice'` | 2 × shared n-grams ÷ (n-grams in `a` + n-grams in `b`). Repeated n-grams are counted. |
303
+ | `'jaccard'` | shared n-grams ÷ all n-grams (counted). |
304
+ | `'cosine'` | Cosine of the two n-gram count vectors. |
305
+ | `'levenshtein'`, `'damerauLevenshtein'` | 1 − distance ÷ length of the longer string. |
306
+ | `'jaro'`, `'jaroWinkler'` | The standard formulas. Transpositions are rounded down, as in Winkler's reference code. |
307
+ | `'lcs'` | 2 × length of the longest common subsequence ÷ (length of `a` + length of `b`). |
308
+ | `'hamming'` | 1 − differing positions ÷ length. Throws a `RangeError` if the lengths differ. |
309
+
310
+ For the n-gram algorithms, two different strings shorter than `n` score `0`, like string-similarity.
311
+
312
+ ### distance(a, b, options?)
313
+
314
+ ```ts
315
+ function distance(a: string, b: string, options?: DistanceOptions): number
316
+ ```
317
+
318
+ Returns the number of edits between two strings. Uses the same text options and defaults as `similarity()`.
319
+
320
+ | Option | Type | Default | What it does |
321
+ |---|---|---|---|
322
+ | `algorithm` | `DistanceAlgorithm` | `'levenshtein'` | `'levenshtein'` (insert, delete, replace), `'damerauLevenshtein'` (also swap two neighbours), `'hamming'` (replace only, same length), or `'lcs'` (insert and delete only). |
323
+ | `maxDistance` | `number` | `Infinity` | Stop counting above this. A result of `maxDistance + 1` means "further than that". |
324
+
325
+ `'damerauLevenshtein'` is the **optimal string alignment** variant: no part of the string is edited twice. So `distance('ca', 'abc', { algorithm: 'damerauLevenshtein' })` is `3`, where the unrestricted version gives `2`.
326
+
327
+ ### rank(query, candidates, options?)
328
+
329
+ ```ts
330
+ function rank<T>(query: string, candidates: readonly T[], options?: MatchOptions<T>): Match<T>[]
331
+ ```
332
+
333
+ Scores every candidate and returns them sorted from highest to lowest rating. Ties keep their input order. Takes every `similarity()` option, plus:
334
+
335
+ | Option | Type | Default | What it does |
336
+ |---|---|---|---|
337
+ | `key` | `string \| (item, index) => string \| null \| undefined` | none | The text to compare for each item. Needed when items are not strings. |
338
+ | `threshold` | `number` | `0` | Drop results with a rating below this. |
339
+ | `limit` | `number` | no limit | Return at most this many results. |
340
+
341
+ ### bestMatch(query, candidates, options?)
342
+
343
+ ```ts
344
+ function bestMatch<T>(query: string, candidates: readonly T[], options?: MatchOptions<T>): Match<T> | undefined
345
+ ```
346
+
347
+ Returns the candidate with the highest rating (the first one on a tie), or `undefined`. Same options as `rank()`.
348
+
349
+ #### Match
350
+
351
+ | Field | Type | What it is |
352
+ |---|---|---|
353
+ | `item` | `T` | The entry from your list. |
354
+ | `target` | `string` | The text that was compared. |
355
+ | `rating` | `number` | The similarity score from 0 to 1. |
356
+ | `index` | `number` | The position of the item in your list. |
357
+
358
+ ### compareTwoStrings(first, second)
359
+
360
+ ```ts
361
+ function compareTwoStrings(first: string, second: string): number
362
+ ```
363
+
364
+ The string-similarity function, unchanged. Removes all whitespace, is case-sensitive, and compares UTF-16 code units with the Dice coefficient. Throws a `TypeError` for non-strings.
365
+
366
+ ### findBestMatch(mainString, targetStrings)
367
+
368
+ ```ts
369
+ function findBestMatch(mainString: string, targetStrings: readonly string[]): BestMatch
370
+ ```
371
+
372
+ The string-similarity function, unchanged. Returns:
373
+
374
+ | Field | Type | What it is |
375
+ |---|---|---|
376
+ | `ratings` | `{ target: string, rating: number }[]` | One rating per target, in input order. |
377
+ | `bestMatch` | `{ target: string, rating: number }` | The highest rating. The first one wins a tie. |
378
+ | `bestMatchIndex` | `number` | The position of `bestMatch` in `targetStrings`. |
379
+
380
+ Throws `Error('Bad arguments: First argument should be a string, second should be an array of strings')` when the arguments are wrong, exactly like string-similarity.
381
+
382
+ ### Other exports
383
+
384
+ | Export | What it does |
385
+ |---|---|
386
+ | `normalize(text, options?)` | Returns the text after the options are applied, so you can see what is compared. |
387
+ | `graphemes(text)` | Splits text into graphemes (the characters a reader sees). |
388
+ | `algorithms` | The list of algorithm names. |
389
+ | `default` | `{ compareTwoStrings, findBestMatch }`, the same object string-similarity exports. |
390
+
391
+ Types: `Algorithm`, `DistanceAlgorithm`, `SimilarityOptions`, `DistanceOptions`, `NormalizeOptions`, `MatchOptions`, `Match`, `KeyName`, `Rating` and `BestMatch`.
392
+
393
+ ## Comparison
394
+
395
+ | | string-similarity | fastest-levenshtein | fuse.js | **similarly** |
396
+ |---|---|---|---|---|
397
+ | Not deprecated | No | Yes | Yes | Yes |
398
+ | TypeScript types included | No | Yes | Yes | Yes |
399
+ | No other packages needed | Yes | Yes | Yes | Yes |
400
+ | ES module build | No | Yes | Yes | Yes |
401
+ | Score from 0 to 1 for two strings | Yes | No | No | Yes |
402
+ | Dice coefficient | Yes | No | No | Yes |
403
+ | Levenshtein distance | No | Yes | No | Yes |
404
+ | Jaro-Winkler | No | No | No | Yes |
405
+ | Best match in a list | Yes | Yes | Yes | Yes |
406
+ | Results sorted by score | No | No | Yes | Yes |
407
+ | Search objects by a field | No | No | Yes | Yes |
408
+ | Threshold and limit | No | No | Yes | Yes |
409
+ | Option to ignore case | No | No | Yes | Yes |
410
+ | Option to ignore accents | No | No | Yes | Yes |
411
+ | Splits text into graphemes (emoji, Indian scripts) | No | No | No | Yes |
412
+
413
+ Checked against string-similarity 4.0.4, fastest-levenshtein 1.0.16 and fuse.js 7.5.0. fuse.js is a full search library: it also finds partial matches inside longer text and can weight several fields, which `similarly` does not do. fastest-levenshtein is faster for plain Levenshtein distance: about 2 times faster on short words in our benchmark.
414
+
415
+ ## Migrating from string-similarity
416
+
417
+ Change the package name. Your code stays the same.
418
+
419
+ ```diff
420
+ - const stringSimilarity = require('string-similarity')
421
+ + const stringSimilarity = require('similarly')
422
+
423
+ stringSimilarity.compareTwoStrings('healed', 'sealed')
424
+ // => 0.8
425
+ stringSimilarity.findBestMatch('healed', ['edward', 'sealed', 'theatre']).bestMatch
426
+ // => { target: 'sealed', rating: 0.8 }
427
+ ```
428
+
429
+ With `import`, both of these work:
430
+
431
+ ```js
432
+ import stringSimilarity from 'similarly'
433
+ import { compareTwoStrings, findBestMatch } from 'similarly'
434
+ ```
435
+
436
+ Then remove the old packages:
437
+
438
+ ```sh
439
+ npm uninstall string-similarity @types/string-similarity
440
+ npm install similarly
441
+ ```
442
+
443
+ The type names `Rating` and `BestMatch` are the same as in `@types/string-similarity`.
444
+
445
+ When you are ready, you can move to the newer functions:
446
+
447
+ | string-similarity | similarly |
448
+ |---|---|
449
+ | `compareTwoStrings(a, b)` | `similarity(a, b, { caseSensitive: true, ignoreWhitespace: true, graphemes: false })` gives the same numbers. Leave out options for case-insensitive, grapheme-aware scores. |
450
+ | `findBestMatch(s, list).bestMatch` | `bestMatch(s, list)` |
451
+ | `findBestMatch(s, list).ratings` | `rank(s, list)` (sorted, with `index`) |
452
+ | `<script src=".../string-similarity.min.js">` | There is no global script build. Use `<script type="module">` and `import` from `https://cdn.jsdelivr.net/npm/similarly@1/dist/index.js`. |
453
+
454
+ ## Notes and limitations
455
+
456
+ - **Not a search engine.** `similarly` compares whole strings. It does not find a word inside a long document, and it has no index. For large lists (more than about 100,000 items), use a search library or database.
457
+ - **Edit distances on long strings.** Levenshtein handles 32 characters per step, so two 1,000-character strings take about 32,000 steps. Damerau-Levenshtein and `'lcs'` check every pair of characters: about 1 million steps for the same strings. Use `maxDistance` when you can, or `'dice'`, which grows with the total length only.
458
+ - **Graphemes and Indian scripts.** A grapheme is a whole syllable, so changing one vowel sign changes the whole grapheme. For typo search in Hindi, Tamil and other Indian scripts, try `graphemes: false` as well and keep what works better for your data.
459
+ - **Grapheme rules depend on the runtime.** `Intl.Segmenter` follows the Unicode version of your JavaScript engine, so some Indian conjuncts may split differently in older browsers. Without `Intl.Segmenter`, a built-in approximation is used. It handles emoji, flags, accents and common conjuncts.
460
+ - **ignoreAccents** removes marks from Latin, Greek and Cyrillic letters. Letters such as `ø`, `ß`, `æ` and `ł` are not changed, because they are separate letters, not accented ones.
461
+ - **Case.** Lowercasing uses `toLowerCase()`, which does not depend on the user's locale. Turkish dotted and dotless `i` may not match the way a Turkish reader expects.
462
+ - **Scores are not percentages of "sameness".** Each algorithm measures something different, so a Dice score of 0.8 and a Jaro-Winkler score of 0.8 do not mean the same thing. Pick one algorithm and choose a `threshold` by testing with your own data.
463
+
464
+ ## Requirements
465
+
466
+ - Node.js 20 or newer, or any modern browser, Deno, Bun or edge runtime.
467
+ - Works with `import` and `require`.
468
+ - TypeScript types included. No other packages needed.
469
+
470
+ ## Credits
471
+
472
+ `compareTwoStrings()` and `findBestMatch()` follow [string-similarity](https://github.com/aceakash/string-similarity) by Akash Kurdekar, version 4.0.4 (copyright 2018 Akash Kurdekar). Its `package.json` lists the ISC licence and its LICENSE file contains the MIT licence text. Both allow reuse with this notice. Thank you for a package that served millions of projects.
473
+
474
+ ## License
475
+
476
+ MIT
package/dist/index.cjs ADDED
@@ -0,0 +1,4 @@
1
+ "use strict";var N=Object.defineProperty;var he=Object.getOwnPropertyDescriptor;var pe=Object.getOwnPropertyNames;var de=Object.prototype.hasOwnProperty;var ye=(e,t)=>{for(var n in t)N(e,n,{get:t[n],enumerable:!0})},be=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of pe(t))!de.call(e,o)&&o!==n&&N(e,o,{get:()=>t[o],enumerable:!(r=he(t,o))||r.enumerable});return e};var we=e=>be(N({},"__esModule",{value:!0}),e);var Re={};ye(Re,{algorithms:()=>E,bestMatch:()=>fe,compareTwoStrings:()=>M,default:()=>Ne,distance:()=>ue,findBestMatch:()=>I,graphemes:()=>se,normalize:()=>re,rank:()=>ge,similarity:()=>ce});module.exports=we(Re);var V=/\s+/g;function M(e,t){if(e=e.replace(V,""),t=t.replace(V,""),e===t)return 1;let n=e.length,r=t.length;if(n<2||r<2)return 0;let o=new Map;for(let s=0;s<n-1;s++){let a=e.charCodeAt(s)*65536+e.charCodeAt(s+1);o.set(a,(o.get(a)??0)+1)}let i=0;for(let s=0;s<r-1;s++){let a=t.charCodeAt(s)*65536+t.charCodeAt(s+1),l=o.get(a);l&&(o.set(a,l-1),i++)}return 2*i/(n+r-2)}function I(e,t){if(!xe(e,t))throw new Error("Bad arguments: First argument should be a string, second should be an array of strings");let n=[],r=0;for(let i=0;i<t.length;i++){let s=t[i],a=M(e,s);n.push({target:s,rating:a}),a>n[r].rating&&(r=i)}let o=n[r];return{ratings:n,bestMatch:o,bestMatchIndex:r}}function xe(e,t){return!(typeof e!="string"||!Array.isArray(t)||!t.length||t.find(n=>typeof n!="string"))}function X(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function z(e,t,n=1/0){if(e.length>t.length){let a=e;e=t,t=a}let r=e.length,o=t.length;if(o-r>n)return n+1;let i=0;for(;i<r&&e[i]===t[i];)i++;for(;r>i&&e[r-1]===t[o-1];)r--,o--;if(r-=i,o-=i,r===0)return o>n?n+1:o;let s=2*n+1<Math.ceil(r/32)*4?Ae(e,t,i,r,o,n):Te(e,t,i,r,o,n);return s>n?n+1:s}var k=new Uint32Array(64);function Ae(e,t,n,r,o,i){if(r===0)return o;k.length<r+1&&(k=new Uint32Array(Math.max(r+1,k.length*2)));let s=k;for(let l=0;l<=r;l++)s[l]=l;let a=i;for(let l=1;l<=o;l++){let c=t[n+l-1],g=l-a>1?l-a:1,u=l+a<r?l+a:r,d,h;g===1?(d=l-1,h=l,s[0]=l):(d=s[g-1],h=i+1);let m=h;for(let f=g;f<=u;f++){let y=s[f],p=e[n+f-1]===c?d:d+1;y+1<p&&(p=y+1),h+1<p&&(p=h+1),s[f]=p,d=y,h=p,p<m&&(m=p)}if(m>i)return i+1}return s[r]}var v=new Int32Array(65536),O=new Map,j=new Int8Array(64);function Te(e,t,n,r,o,i){if(r===0)return o;j.length<o&&(j=new Int8Array(Math.max(o,j.length*2)));let s=j;s.fill(1,0,o);let a=0;for(let l=0;l<r;l+=32){let c=Math.min(32,r-l),g=1<<c-1;for(let m=0;m<c;m++){let f=e[n+l+m];f<65536?v[f]=v[f]|1<<m:O.set(f,(O.get(f)??0)|1<<m)}let u=-1,d=0;a=l+c;let h=c===r;for(let m=0;m<o;m++){let f=t[n+m],y=f<65536?v[f]:O.get(f)??0,p=s[m],S=p>0?1:0,F=p<0?1:0,_=y|d,H=y|F,J=(H&u)+u^u|H,T=d|~(J|u),U=u&J;if(T&g?(s[m]=1,a++):U&g?(s[m]=-1,a--):s[m]=0,T=T<<1|S,U=U<<1|F,u=U|~(_|T),d=T&_,h&&a-(o-m-1)>i){a=i+1;break}}for(let m=0;m<c;m++){let f=e[n+l+m];f<65536?v[f]=0:O.delete(f)}}return a}function $(e,t,n=1/0){if(e.length>t.length){let c=e;e=t,t=c}let r=e.length,o=t.length;if(o-r>n)return n+1;if(r===0)return o>n?n+1:o;let i=new Uint32Array(r+1),s=new Uint32Array(r+1),a=new Uint32Array(r+1);for(let c=0;c<=r;c++)s[c]=c;for(let c=1;c<=o;c++){let g=t[c-1];a[0]=c;let u=c;for(let h=1;h<=r;h++){let m=e[h-1],f=s[h-1]+(m===g?0:1),y=s[h]+1,p=a[h-1]+1;if(y<f&&(f=y),p<f&&(f=p),h>1&&c>1&&m===t[c-2]&&e[h-2]===g){let S=i[h-2]+1;S<f&&(f=S)}a[h]=f,f<u&&(u=f)}if(u>n)return n+1;let d=i;i=s,s=a,a=d}let l=s[r];return l>n?n+1:l}function D(e,t){if(e.length!==t.length)throw new RangeError(`similarly: hamming needs two strings of the same length, got ${e.length} and ${t.length} characters`);let n=0;for(let r=0;r<e.length;r++)e[r]!==t[r]&&n++;return n}function B(e,t){if(e.length<t.length){let a=e;e=t,t=a}let n=e.length,r=t.length,o=0;for(;o<r&&e[o]===t[o];)o++;let i=o;for(;r>o&&e[n-1]===t[r-1];)n--,r--,i++;if(n-=o,r-=o,r===0)return i;let s=new Uint32Array(r+1);for(let a=0;a<n;a++){let l=e[o+a],c=0;for(let g=0;g<r;g++){let u=s[g+1];l===t[o+g]?s[g+1]=c+1:s[g]>u&&(s[g+1]=s[g]),c=u}}return i+s[r]}function Me(e,t){if(e.length!==t.length)return e.length-t.length;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return e[n]-t[n];return 0}function C(e,t){if(Me(e,t)>0){let u=e;e=t,t=u}let n=e.length,r=t.length;if(n===0||r===0)return n===r?1:0;let o=Math.max(0,Math.floor(Math.max(n,r)/2)-1),i=new Uint8Array(n),s=new Uint8Array(r),a=0;for(let u=0;u<n;u++){let d=Math.max(0,u-o),h=Math.min(r-1,u+o);for(let m=d;m<=h;m++)if(!s[m]&&e[u]===t[m]){i[u]=1,s[m]=1,a++;break}}if(a===0)return 0;let l=0,c=0;for(let u=0;u<n;u++)if(i[u]){for(;!s[c];)c++;e[u]!==t[c]&&l++,c++}let g=Math.floor(l/2);return(a/n+a/r+(a-g)/a)/3}function Z(e,t,n,r,o){let i=C(e,t);if(i<=o)return i;let s=Math.min(r,e.length,t.length),a=0;for(;a<s&&e[a]===t[a];)a++;return Math.min(1,i+a*n*(1-i))}var R=2097152;function Y(e,t,n){let r=e.length-t+1,o=new Array(Math.max(0,r));for(let i=0;i<r;i++)if(t===1)o[i]=e[i];else if(t===2&&n)o[i]=e[i]*R+e[i+1];else{let s=String(e[i]);for(let a=1;a<t;a++)s+=","+e[i+a];o[i]=s}return o}function Q(e){let t=0;for(let n=0;n<e.length;n++)e[n]>t&&(t=e[n]);return t}function P(e,t,n){let r=n!==2||Q(e)<R&&Q(t)<R,o=new Map;for(let i of Y(e,n,r))o.set(i,(o.get(i)??0)+1);return[o,Y(t,n,r)]}function ee(e,t,n){if(e.length<n||t.length<n)return 0;let[r,o]=P(e,t,n),i=0;for(let s of o){let a=r.get(s);a&&(r.set(s,a-1),i++)}return 2*i/(e.length-n+1+(t.length-n+1))}function te(e,t,n){if(e.length<n||t.length<n)return 0;let[r,o]=P(e,t,n),i=0;for(let a of o){let l=r.get(a);l&&(r.set(a,l-1),i++)}let s=e.length-n+1+(t.length-n+1);return i/(s-i)}function ne(e,t,n){if(e.length<n||t.length<n)return 0;let[r,o]=P(e,t,n),i=new Map;for(let c of o)i.set(c,(i.get(c)??0)+1);let s=0,a=0,l=0;for(let[c,g]of r){a+=g*g;let u=i.get(c);u&&(s+=g*u)}for(let c of i.values())l+=c*c;return Math.min(1,s/Math.sqrt(a*l))}var Se=/\s+/g,Ue=/\p{P}+/gu,Ie=/[̀-ͯ᪰-᫿᷀-᷿⃐-⃿︠-︯]/g,G=/^[\u0000-˿]*$/,ke=/[^\u0000-\u007f]/;function re(e,t={}){return b(e,"text"),W(e,t??{})}function W(e,t){let n=G.test(e)?e:e.normalize("NFC");return t.caseSensitive||(n=n.toLowerCase()),t.ignoreAccents&&ke.test(n)&&(n=n.normalize("NFKD").replace(Ie,"").normalize("NFC")),t.ignorePunctuation&&(n=n.replace(Ue,"")),t.ignoreWhitespace&&(n=n.replace(Se,"")),n}var L;function ie(){if(L===void 0){let e=globalThis.Intl?.Segmenter;L=typeof e=="function"?new e(void 0,{granularity:"grapheme"}):null}return L}var ve=/\r\n|\p{Regional_Indicator}{2}|[^\p{M}‍](?:‍\p{Extended_Pictographic}|[्্્୍్്]‍?\p{L}|[\p{M}‌‍︎️\u{1f3fb}-\u{1f3ff}\u{e0020}-\u{e007f}])*|[\s\S]/gu;function oe(e){return e.match(ve)??[]}function se(e){if(b(e,"text"),G.test(e)&&e.indexOf(`\r
2
+ `)===-1)return e.split("");let t=ie();if(!t)return oe(e);let n=[];for(let r of t.segment(e))n.push(r.segment);return n}var x=class{constructor(){this.next=65536}id(t){if(t.length===1)return t.charCodeAt(0);let n=this.ids??(this.ids=new Map),r=n.get(t);return r===void 0&&(r=this.next++,n.set(t,r)),r}};function ae(e,t,n){if(!t||G.test(e)&&e.indexOf(`\r
3
+ `)===-1){let s=new Int32Array(e.length);for(let a=0;a<e.length;a++)s[a]=e.charCodeAt(a);return s}let r=ie(),o=r?r.segment(e):oe(e),i=[];for(let s of o)i.push(n.id(typeof s=="string"?s:s.segment));return Int32Array.from(i)}function b(e,t){if(typeof e!="string")throw new TypeError(`similarly: ${t} must be a string, got ${w(e)}`)}function w(e){if(e===null)return"null";if(Array.isArray(e))return"an array";let t=typeof e;return t==="object"?"an object":t==="undefined"?"undefined":`a ${t}`}var E=Object.freeze(["dice","levenshtein","damerauLevenshtein","jaro","jaroWinkler","jaccard","cosine","lcs","hamming"]),le=["levenshtein","damerauLevenshtein","hamming","lcs"];function Oe(e){return typeof e=="string"&&E.includes(e)}function q(e){let t=e??{},n=t.algorithm??"dice";if(!Oe(n))throw new RangeError(`similarly: unknown algorithm ${JSON.stringify(n)}. Use one of: ${E.join(", ")}`);let r=t.n??2;if(!Number.isInteger(r)||r<1)throw new RangeError(`similarly: n must be a whole number of 1 or more, got ${String(r)}`);let o=t.prefixScale??.1,i=t.maxPrefix??4,s=t.boostThreshold??.7;if(!Number.isInteger(i)||i<0)throw new RangeError(`similarly: maxPrefix must be a whole number of 0 or more, got ${String(i)}`);if(typeof o!="number"||!(o>=0)||o*i>1)throw new RangeError(`similarly: prefixScale must be 0 or more, and prefixScale * maxPrefix must be 1 or less, got ${String(o)}`);if(typeof s!="number"||!(s>=0&&s<=1))throw new RangeError(`similarly: boostThreshold must be from 0 to 1, got ${String(s)}`);return{algorithm:n,normalize:t,graphemes:t.graphemes??!0,n:r,prefixScale:o,maxPrefix:i,boostThreshold:s}}function A(e,t,n){return ae(W(e,t.normalize),t.graphemes,n)}function K(e,t,n){if(n.algorithm==="hamming"){let r=D(e,t);return e.length===0?1:1-r/e.length}if(X(e,t))return 1;switch(n.algorithm){case"dice":return ee(e,t,n.n);case"jaccard":return te(e,t,n.n);case"cosine":return ne(e,t,n.n);case"levenshtein":return 1-z(e,t)/Math.max(e.length,t.length);case"damerauLevenshtein":return 1-$(e,t)/Math.max(e.length,t.length);case"jaro":return C(e,t);case"jaroWinkler":return Z(e,t,n.prefixScale,n.maxPrefix,n.boostThreshold);case"lcs":return 2*B(e,t)/(e.length+t.length)}}function ce(e,t,n){b(e,"the first argument"),b(t,"the second argument");let r=q(n),o=new x;return K(A(e,r,o),A(t,r,o),r)}function ue(e,t,n){b(e,"the first argument"),b(t,"the second argument");let r=n??{},o=r.algorithm??"levenshtein";if(!le.includes(o))throw new RangeError(`similarly: distance() supports ${le.join(", ")}, got ${typeof o=="string"?JSON.stringify(o):w(o)}. Use similarity() for the others`);let i=r.maxDistance??1/0;if(!(Number.isInteger(i)||i===1/0)||i<0)throw new RangeError(`similarly: maxDistance must be a whole number of 0 or more, got ${String(i)}`);let s=new x,a={normalize:r,graphemes:r.graphemes??!0},l=A(e,a,s),c=A(t,a,s),g;switch(o){case"levenshtein":return z(l,c,i);case"damerauLevenshtein":return $(l,c,i);case"hamming":g=D(l,c);break;case"lcs":if(Math.abs(l.length-c.length)>i)return i+1;g=l.length+c.length-2*B(l,c);break}return g>i?i+1:g}function je(e){if(e===void 0)return(n,r)=>{if(typeof n!="string")throw new TypeError(`similarly: candidate at index ${r} is ${w(n)}, not a string. Use the key option to compare objects`);return n};let t=typeof e=="function"?e:typeof e=="string"?n=>n?.[e]:(()=>{throw new TypeError(`similarly: key must be a property name or a function, got ${w(e)}`)})();return(n,r)=>{let o=t(n,r);if(o!=null){if(typeof o!="string")throw new TypeError(`similarly: key value at index ${r} is ${w(o)}, not a string`);return o}}}function me(e,t,n){if(b(e,"the query"),!Array.isArray(t))throw new TypeError(`similarly: candidates must be an array, got ${w(t)}`);let r=n??{},o=q(r),i=r.threshold??0;if(typeof i!="number"||!(i>=0&&i<=1))throw new RangeError(`similarly: threshold must be from 0 to 1, got ${String(i)}`);let s=r.limit??1/0;if(!(Number.isInteger(s)||s===1/0)||s<0)throw new RangeError(`similarly: limit must be a whole number of 0 or more, got ${String(s)}`);let a=new x,l=A(e,o,a);return{query:l,get:je(r.key),threshold:i,limit:s,each:c=>K(l,A(c,o,a),o)}}function ge(e,t,n){let r=me(e,t,n),o=[];if(r.limit===0)return o;for(let i=0;i<t.length;i++){let s=t[i],a=r.get(s,i);if(a===void 0)continue;let l=r.each(a);l>=r.threshold&&o.push({item:s,target:a,rating:l,index:i})}return o.sort((i,s)=>s.rating-i.rating),o.length>r.limit&&(o.length=r.limit),o}function fe(e,t,n){let r=me(e,t,n),o;if(r.limit===0)return o;for(let i=0;i<t.length;i++){let s=t[i],a=r.get(s,i);if(a===void 0)continue;let l=r.each(a);l>=r.threshold&&(o===void 0||l>o.rating)&&(o={item:s,target:a,rating:l,index:i})}return o}var Ee={compareTwoStrings:M,findBestMatch:I},Ne=Ee;0&&(module.exports={algorithms,bestMatch,compareTwoStrings,distance,findBestMatch,graphemes,normalize,rank,similarity});
4
+ var __d=module.exports.default;for(var __k in module.exports)if(!(__k in __d))__d[__k]=module.exports[__k];__d.default=__d;module.exports=__d;
@@ -0,0 +1,226 @@
1
+ /**
2
+ * The two functions of the deprecated `string-similarity` package (version 4),
3
+ * with the same results, return shapes and errors.
4
+ *
5
+ * Based on string-similarity 4.0.4 by Akash Kurdekar (https://github.com/aceakash/string-similarity),
6
+ * copyright (c) 2018 Akash Kurdekar. Its package.json lists the ISC licence; its LICENSE file has MIT text.
7
+ */
8
+ /** One target string and its similarity score, as returned by {@link findBestMatch}. */
9
+ interface Rating {
10
+ /** The target string that was compared. */
11
+ target: string;
12
+ /** The similarity score from 0 (nothing in common) to 1 (the same). */
13
+ rating: number;
14
+ }
15
+ /** The result of {@link findBestMatch}. */
16
+ interface BestMatch {
17
+ /** One rating per target string, in the same order as the input. */
18
+ ratings: Rating[];
19
+ /** The rating with the highest score. When scores tie, the first one wins. */
20
+ bestMatch: Rating;
21
+ /** The position of `bestMatch` in the target list. */
22
+ bestMatchIndex: number;
23
+ }
24
+ /**
25
+ * Compares two strings and returns a similarity score from 0 to 1, using the
26
+ * Dice coefficient on pairs of adjacent characters (bigrams).
27
+ *
28
+ * Works exactly like `compareTwoStrings` in string-similarity 4: whitespace is
29
+ * removed, upper and lower case are different, and strings are split into
30
+ * UTF-16 code units. For grapheme-aware, case-insensitive comparison use
31
+ * {@link similarity} instead.
32
+ *
33
+ * @example
34
+ * compareTwoStrings('healed', 'sealed') // => 0.8
35
+ */
36
+ declare function compareTwoStrings(first: string, second: string): number;
37
+ /**
38
+ * Compares one string with a list of strings and finds the most similar one.
39
+ *
40
+ * Works exactly like `findBestMatch` in string-similarity 4. It throws
41
+ * `Error('Bad arguments: ...')` when the first argument is not a string, or the
42
+ * second is not a non-empty array of strings.
43
+ *
44
+ * @example
45
+ * findBestMatch('healed', ['edward', 'sealed', 'theatre']).bestMatch
46
+ * // => { target: 'sealed', rating: 0.8 }
47
+ */
48
+ declare function findBestMatch(mainString: string, targetStrings: readonly string[]): BestMatch;
49
+
50
+ /** Options that change the text before it is compared. */
51
+ interface NormalizeOptions {
52
+ /** Treat upper and lower case as different. Default `false`. */
53
+ caseSensitive?: boolean;
54
+ /** Remove all spaces, tabs and line breaks before comparing. Default `false`. */
55
+ ignoreWhitespace?: boolean;
56
+ /** Remove punctuation (Unicode category P, such as `.,!?-'"` and the Devanagari danda `।`). Default `false`. */
57
+ ignorePunctuation?: boolean;
58
+ /**
59
+ * Remove accent marks from letters, so `café` matches `cafe`. Uses Unicode
60
+ * NFKD and removes combining diacritical marks. Vowel signs in Indian scripts
61
+ * are kept, because they change the word. Default `false`.
62
+ */
63
+ ignoreAccents?: boolean;
64
+ /**
65
+ * Compare by grapheme (what a reader sees as one character), so an emoji or
66
+ * a Hindi syllable like `स्ते` counts as one character. Uses `Intl.Segmenter`
67
+ * when the runtime has it. `false` compares UTF-16 code units, which is
68
+ * faster but splits emoji. Default `true`.
69
+ */
70
+ graphemes?: boolean;
71
+ }
72
+ /**
73
+ * Applies the normalisation options to a string and returns the text that
74
+ * would be compared. Text is first put into Unicode NFC form, so `é` typed as
75
+ * one character or as `e` plus an accent are the same.
76
+ *
77
+ * @example
78
+ * normalize('Crème Brûlée!', { ignoreAccents: true, ignorePunctuation: true }) // => 'creme brulee'
79
+ */
80
+ declare function normalize(text: string, options?: NormalizeOptions): string;
81
+ /**
82
+ * Splits a string into graphemes: the characters a reader sees. An emoji with
83
+ * a skin tone, a flag, or a Hindi syllable stays in one piece. Uses
84
+ * `Intl.Segmenter` when available, and a close approximation otherwise.
85
+ *
86
+ * @example
87
+ * graphemes('नमस्ते 👍🏽') // => ['न', 'म', 'स्ते', ' ', '👍🏽']
88
+ */
89
+ declare function graphemes(text: string): string[];
90
+
91
+ /**
92
+ * The algorithms {@link similarity} can use.
93
+ *
94
+ * - `'dice'` (default): shared pairs of characters. Same method as string-similarity.
95
+ * - `'levenshtein'`: edit distance (insert, delete, replace).
96
+ * - `'damerauLevenshtein'`: edit distance that also counts swapping two neighbours as one edit (optimal string alignment variant).
97
+ * - `'jaro'`, `'jaroWinkler'`: matching characters nearby; Jaro-Winkler gives extra weight to a shared start. Good for names.
98
+ * - `'jaccard'`, `'cosine'`: shared n-grams, two other ways to score them.
99
+ * - `'lcs'`: longest common subsequence.
100
+ * - `'hamming'`: positions that differ. Strings must have the same length.
101
+ */
102
+ type Algorithm = 'dice' | 'levenshtein' | 'damerauLevenshtein' | 'jaro' | 'jaroWinkler' | 'jaccard' | 'cosine' | 'lcs' | 'hamming';
103
+ /** The algorithms {@link distance} can use. */
104
+ type DistanceAlgorithm = 'levenshtein' | 'damerauLevenshtein' | 'hamming' | 'lcs';
105
+ /** Every algorithm name, in the order shown in the docs. */
106
+ declare const algorithms: readonly Algorithm[];
107
+ /** Options for {@link similarity}. */
108
+ interface SimilarityOptions extends NormalizeOptions {
109
+ /** Which algorithm to use. Default `'dice'`. */
110
+ algorithm?: Algorithm;
111
+ /** n-gram size for `'dice'`, `'jaccard'` and `'cosine'`. Default `2` (pairs of characters). */
112
+ n?: number;
113
+ /** Jaro-Winkler: weight for each shared starting character. Default `0.1`. */
114
+ prefixScale?: number;
115
+ /** Jaro-Winkler: how many starting characters can count. Default `4`. */
116
+ maxPrefix?: number;
117
+ /** Jaro-Winkler: only add the prefix bonus when the Jaro score is above this. Default `0.7`. Use `0` to always add it. */
118
+ boostThreshold?: number;
119
+ }
120
+ /** Options for {@link distance}. */
121
+ interface DistanceOptions extends NormalizeOptions {
122
+ /** Which distance to measure. Default `'levenshtein'`. */
123
+ algorithm?: DistanceAlgorithm;
124
+ /**
125
+ * Stop counting above this distance. When the real distance is larger, the
126
+ * result is `maxDistance + 1`. Makes `'levenshtein'` and
127
+ * `'damerauLevenshtein'` much faster for "is it close?" checks.
128
+ * Default `Infinity`.
129
+ */
130
+ maxDistance?: number;
131
+ }
132
+ /**
133
+ * Returns how similar two strings are, as a number from 0 (nothing in common)
134
+ * to 1 (the same after normalisation).
135
+ *
136
+ * By default it uses the Dice coefficient (like string-similarity), ignores
137
+ * case, and compares graphemes, so emoji and Indian scripts are not split.
138
+ *
139
+ * @example
140
+ * similarity('Healed', 'sealed') // => 0.8
141
+ * similarity('MARTHA', 'MARHTA', { algorithm: 'jaroWinkler' }) // => 0.9611...
142
+ */
143
+ declare function similarity(a: string, b: string, options?: SimilarityOptions): number;
144
+ /**
145
+ * Returns the edit distance between two strings: how many single-character
146
+ * changes turn one into the other.
147
+ *
148
+ * - `'levenshtein'` (default): insertions, deletions and replacements.
149
+ * - `'damerauLevenshtein'`: also swaps of two neighbouring characters (optimal string alignment variant).
150
+ * - `'hamming'`: replacements only. The strings must have the same length.
151
+ * - `'lcs'`: insertions and deletions only (length of both minus twice the longest common subsequence).
152
+ *
153
+ * Uses the same normalisation options and defaults as {@link similarity}.
154
+ *
155
+ * @example
156
+ * distance('kitten', 'sitting') // => 3
157
+ * distance('kitten', 'sitting', { maxDistance: 1 }) // => 2 (more than 1)
158
+ */
159
+ declare function distance(a: string, b: string, options?: DistanceOptions): number;
160
+
161
+ /** A property name of `T`, with editor suggestions, or any other string. */
162
+ type KeyName<T> = Extract<keyof T, string> | (string & {});
163
+ /** Options for {@link rank} and {@link bestMatch}. */
164
+ interface MatchOptions<T> extends SimilarityOptions {
165
+ /**
166
+ * Which text to compare when the candidates are objects: a property name,
167
+ * or a function that returns the text. Items where it gives `null` or
168
+ * `undefined` are skipped.
169
+ */
170
+ key?: KeyName<T> | ((item: T, index: number) => string | null | undefined);
171
+ /** Drop results with a rating below this (0 to 1). Default `0` (keep all). */
172
+ threshold?: number;
173
+ /** Return at most this many results. Default: no limit. */
174
+ limit?: number;
175
+ }
176
+ /** One ranked candidate. */
177
+ interface Match<T> {
178
+ /** The candidate from your list (a string, or your object). */
179
+ item: T;
180
+ /** The text that was compared (the string itself, or the `key` value). */
181
+ target: string;
182
+ /** The similarity score from 0 to 1. */
183
+ rating: number;
184
+ /** The position of the item in your list. */
185
+ index: number;
186
+ }
187
+ /**
188
+ * Scores every candidate against the query and returns them from most to least
189
+ * similar. Candidates with the same rating keep their original order.
190
+ *
191
+ * @example
192
+ * rank('appel', ['apple', 'maple', 'apply', 'banana'], { limit: 2 })
193
+ * // => [{ item: 'apple', target: 'apple', rating: 0.5, index: 0 }, { item: 'apply', ... }]
194
+ */
195
+ declare function rank<T>(query: string, candidates: readonly T[], options?: MatchOptions<T>): Match<T>[];
196
+ /**
197
+ * Returns the candidate most similar to the query, or `undefined` when the list
198
+ * is empty or nothing reaches the `threshold`. When ratings tie, the first one wins.
199
+ *
200
+ * @example
201
+ * bestMatch('healed', ['edward', 'sealed', 'theatre'])
202
+ * // => { item: 'sealed', target: 'sealed', rating: 0.8, index: 1 }
203
+ */
204
+ declare function bestMatch<T>(query: string, candidates: readonly T[], options?: MatchOptions<T>): Match<T> | undefined;
205
+
206
+ /**
207
+ * similarly: compare how similar two strings are and find the best match in a list.
208
+ * A drop-in replacement for the deprecated string-similarity, with more algorithms.
209
+ *
210
+ * compareTwoStrings('healed', 'sealed') // 0.8
211
+ * similarity('MARTHA', 'MARHTA', { algorithm: 'jaroWinkler' }) // 0.961...
212
+ * bestMatch('appel', ['apple', 'maple', 'banana'])?.item // 'apple'
213
+ * distance('kitten', 'sitting') // 3
214
+ */
215
+
216
+ /**
217
+ * The same object that string-similarity exports, so
218
+ * `import stringSimilarity from 'similarly'` and
219
+ * `const stringSimilarity = require('similarly')` keep working.
220
+ */
221
+ declare const stringSimilarity: {
222
+ compareTwoStrings: typeof compareTwoStrings;
223
+ findBestMatch: typeof findBestMatch;
224
+ };
225
+
226
+ export { type Algorithm, type BestMatch, type DistanceAlgorithm, type DistanceOptions, type KeyName, type Match, type MatchOptions, type NormalizeOptions, type Rating, type SimilarityOptions, algorithms, bestMatch, compareTwoStrings, stringSimilarity as default, distance, findBestMatch, graphemes, normalize, rank, similarity };
@@ -0,0 +1,226 @@
1
+ /**
2
+ * The two functions of the deprecated `string-similarity` package (version 4),
3
+ * with the same results, return shapes and errors.
4
+ *
5
+ * Based on string-similarity 4.0.4 by Akash Kurdekar (https://github.com/aceakash/string-similarity),
6
+ * copyright (c) 2018 Akash Kurdekar. Its package.json lists the ISC licence; its LICENSE file has MIT text.
7
+ */
8
+ /** One target string and its similarity score, as returned by {@link findBestMatch}. */
9
+ interface Rating {
10
+ /** The target string that was compared. */
11
+ target: string;
12
+ /** The similarity score from 0 (nothing in common) to 1 (the same). */
13
+ rating: number;
14
+ }
15
+ /** The result of {@link findBestMatch}. */
16
+ interface BestMatch {
17
+ /** One rating per target string, in the same order as the input. */
18
+ ratings: Rating[];
19
+ /** The rating with the highest score. When scores tie, the first one wins. */
20
+ bestMatch: Rating;
21
+ /** The position of `bestMatch` in the target list. */
22
+ bestMatchIndex: number;
23
+ }
24
+ /**
25
+ * Compares two strings and returns a similarity score from 0 to 1, using the
26
+ * Dice coefficient on pairs of adjacent characters (bigrams).
27
+ *
28
+ * Works exactly like `compareTwoStrings` in string-similarity 4: whitespace is
29
+ * removed, upper and lower case are different, and strings are split into
30
+ * UTF-16 code units. For grapheme-aware, case-insensitive comparison use
31
+ * {@link similarity} instead.
32
+ *
33
+ * @example
34
+ * compareTwoStrings('healed', 'sealed') // => 0.8
35
+ */
36
+ declare function compareTwoStrings(first: string, second: string): number;
37
+ /**
38
+ * Compares one string with a list of strings and finds the most similar one.
39
+ *
40
+ * Works exactly like `findBestMatch` in string-similarity 4. It throws
41
+ * `Error('Bad arguments: ...')` when the first argument is not a string, or the
42
+ * second is not a non-empty array of strings.
43
+ *
44
+ * @example
45
+ * findBestMatch('healed', ['edward', 'sealed', 'theatre']).bestMatch
46
+ * // => { target: 'sealed', rating: 0.8 }
47
+ */
48
+ declare function findBestMatch(mainString: string, targetStrings: readonly string[]): BestMatch;
49
+
50
+ /** Options that change the text before it is compared. */
51
+ interface NormalizeOptions {
52
+ /** Treat upper and lower case as different. Default `false`. */
53
+ caseSensitive?: boolean;
54
+ /** Remove all spaces, tabs and line breaks before comparing. Default `false`. */
55
+ ignoreWhitespace?: boolean;
56
+ /** Remove punctuation (Unicode category P, such as `.,!?-'"` and the Devanagari danda `।`). Default `false`. */
57
+ ignorePunctuation?: boolean;
58
+ /**
59
+ * Remove accent marks from letters, so `café` matches `cafe`. Uses Unicode
60
+ * NFKD and removes combining diacritical marks. Vowel signs in Indian scripts
61
+ * are kept, because they change the word. Default `false`.
62
+ */
63
+ ignoreAccents?: boolean;
64
+ /**
65
+ * Compare by grapheme (what a reader sees as one character), so an emoji or
66
+ * a Hindi syllable like `स्ते` counts as one character. Uses `Intl.Segmenter`
67
+ * when the runtime has it. `false` compares UTF-16 code units, which is
68
+ * faster but splits emoji. Default `true`.
69
+ */
70
+ graphemes?: boolean;
71
+ }
72
+ /**
73
+ * Applies the normalisation options to a string and returns the text that
74
+ * would be compared. Text is first put into Unicode NFC form, so `é` typed as
75
+ * one character or as `e` plus an accent are the same.
76
+ *
77
+ * @example
78
+ * normalize('Crème Brûlée!', { ignoreAccents: true, ignorePunctuation: true }) // => 'creme brulee'
79
+ */
80
+ declare function normalize(text: string, options?: NormalizeOptions): string;
81
+ /**
82
+ * Splits a string into graphemes: the characters a reader sees. An emoji with
83
+ * a skin tone, a flag, or a Hindi syllable stays in one piece. Uses
84
+ * `Intl.Segmenter` when available, and a close approximation otherwise.
85
+ *
86
+ * @example
87
+ * graphemes('नमस्ते 👍🏽') // => ['न', 'म', 'स्ते', ' ', '👍🏽']
88
+ */
89
+ declare function graphemes(text: string): string[];
90
+
91
+ /**
92
+ * The algorithms {@link similarity} can use.
93
+ *
94
+ * - `'dice'` (default): shared pairs of characters. Same method as string-similarity.
95
+ * - `'levenshtein'`: edit distance (insert, delete, replace).
96
+ * - `'damerauLevenshtein'`: edit distance that also counts swapping two neighbours as one edit (optimal string alignment variant).
97
+ * - `'jaro'`, `'jaroWinkler'`: matching characters nearby; Jaro-Winkler gives extra weight to a shared start. Good for names.
98
+ * - `'jaccard'`, `'cosine'`: shared n-grams, two other ways to score them.
99
+ * - `'lcs'`: longest common subsequence.
100
+ * - `'hamming'`: positions that differ. Strings must have the same length.
101
+ */
102
+ type Algorithm = 'dice' | 'levenshtein' | 'damerauLevenshtein' | 'jaro' | 'jaroWinkler' | 'jaccard' | 'cosine' | 'lcs' | 'hamming';
103
+ /** The algorithms {@link distance} can use. */
104
+ type DistanceAlgorithm = 'levenshtein' | 'damerauLevenshtein' | 'hamming' | 'lcs';
105
+ /** Every algorithm name, in the order shown in the docs. */
106
+ declare const algorithms: readonly Algorithm[];
107
+ /** Options for {@link similarity}. */
108
+ interface SimilarityOptions extends NormalizeOptions {
109
+ /** Which algorithm to use. Default `'dice'`. */
110
+ algorithm?: Algorithm;
111
+ /** n-gram size for `'dice'`, `'jaccard'` and `'cosine'`. Default `2` (pairs of characters). */
112
+ n?: number;
113
+ /** Jaro-Winkler: weight for each shared starting character. Default `0.1`. */
114
+ prefixScale?: number;
115
+ /** Jaro-Winkler: how many starting characters can count. Default `4`. */
116
+ maxPrefix?: number;
117
+ /** Jaro-Winkler: only add the prefix bonus when the Jaro score is above this. Default `0.7`. Use `0` to always add it. */
118
+ boostThreshold?: number;
119
+ }
120
+ /** Options for {@link distance}. */
121
+ interface DistanceOptions extends NormalizeOptions {
122
+ /** Which distance to measure. Default `'levenshtein'`. */
123
+ algorithm?: DistanceAlgorithm;
124
+ /**
125
+ * Stop counting above this distance. When the real distance is larger, the
126
+ * result is `maxDistance + 1`. Makes `'levenshtein'` and
127
+ * `'damerauLevenshtein'` much faster for "is it close?" checks.
128
+ * Default `Infinity`.
129
+ */
130
+ maxDistance?: number;
131
+ }
132
+ /**
133
+ * Returns how similar two strings are, as a number from 0 (nothing in common)
134
+ * to 1 (the same after normalisation).
135
+ *
136
+ * By default it uses the Dice coefficient (like string-similarity), ignores
137
+ * case, and compares graphemes, so emoji and Indian scripts are not split.
138
+ *
139
+ * @example
140
+ * similarity('Healed', 'sealed') // => 0.8
141
+ * similarity('MARTHA', 'MARHTA', { algorithm: 'jaroWinkler' }) // => 0.9611...
142
+ */
143
+ declare function similarity(a: string, b: string, options?: SimilarityOptions): number;
144
+ /**
145
+ * Returns the edit distance between two strings: how many single-character
146
+ * changes turn one into the other.
147
+ *
148
+ * - `'levenshtein'` (default): insertions, deletions and replacements.
149
+ * - `'damerauLevenshtein'`: also swaps of two neighbouring characters (optimal string alignment variant).
150
+ * - `'hamming'`: replacements only. The strings must have the same length.
151
+ * - `'lcs'`: insertions and deletions only (length of both minus twice the longest common subsequence).
152
+ *
153
+ * Uses the same normalisation options and defaults as {@link similarity}.
154
+ *
155
+ * @example
156
+ * distance('kitten', 'sitting') // => 3
157
+ * distance('kitten', 'sitting', { maxDistance: 1 }) // => 2 (more than 1)
158
+ */
159
+ declare function distance(a: string, b: string, options?: DistanceOptions): number;
160
+
161
+ /** A property name of `T`, with editor suggestions, or any other string. */
162
+ type KeyName<T> = Extract<keyof T, string> | (string & {});
163
+ /** Options for {@link rank} and {@link bestMatch}. */
164
+ interface MatchOptions<T> extends SimilarityOptions {
165
+ /**
166
+ * Which text to compare when the candidates are objects: a property name,
167
+ * or a function that returns the text. Items where it gives `null` or
168
+ * `undefined` are skipped.
169
+ */
170
+ key?: KeyName<T> | ((item: T, index: number) => string | null | undefined);
171
+ /** Drop results with a rating below this (0 to 1). Default `0` (keep all). */
172
+ threshold?: number;
173
+ /** Return at most this many results. Default: no limit. */
174
+ limit?: number;
175
+ }
176
+ /** One ranked candidate. */
177
+ interface Match<T> {
178
+ /** The candidate from your list (a string, or your object). */
179
+ item: T;
180
+ /** The text that was compared (the string itself, or the `key` value). */
181
+ target: string;
182
+ /** The similarity score from 0 to 1. */
183
+ rating: number;
184
+ /** The position of the item in your list. */
185
+ index: number;
186
+ }
187
+ /**
188
+ * Scores every candidate against the query and returns them from most to least
189
+ * similar. Candidates with the same rating keep their original order.
190
+ *
191
+ * @example
192
+ * rank('appel', ['apple', 'maple', 'apply', 'banana'], { limit: 2 })
193
+ * // => [{ item: 'apple', target: 'apple', rating: 0.5, index: 0 }, { item: 'apply', ... }]
194
+ */
195
+ declare function rank<T>(query: string, candidates: readonly T[], options?: MatchOptions<T>): Match<T>[];
196
+ /**
197
+ * Returns the candidate most similar to the query, or `undefined` when the list
198
+ * is empty or nothing reaches the `threshold`. When ratings tie, the first one wins.
199
+ *
200
+ * @example
201
+ * bestMatch('healed', ['edward', 'sealed', 'theatre'])
202
+ * // => { item: 'sealed', target: 'sealed', rating: 0.8, index: 1 }
203
+ */
204
+ declare function bestMatch<T>(query: string, candidates: readonly T[], options?: MatchOptions<T>): Match<T> | undefined;
205
+
206
+ /**
207
+ * similarly: compare how similar two strings are and find the best match in a list.
208
+ * A drop-in replacement for the deprecated string-similarity, with more algorithms.
209
+ *
210
+ * compareTwoStrings('healed', 'sealed') // 0.8
211
+ * similarity('MARTHA', 'MARHTA', { algorithm: 'jaroWinkler' }) // 0.961...
212
+ * bestMatch('appel', ['apple', 'maple', 'banana'])?.item // 'apple'
213
+ * distance('kitten', 'sitting') // 3
214
+ */
215
+
216
+ /**
217
+ * The same object that string-similarity exports, so
218
+ * `import stringSimilarity from 'similarly'` and
219
+ * `const stringSimilarity = require('similarly')` keep working.
220
+ */
221
+ declare const stringSimilarity: {
222
+ compareTwoStrings: typeof compareTwoStrings;
223
+ findBestMatch: typeof findBestMatch;
224
+ };
225
+
226
+ export { type Algorithm, type BestMatch, type DistanceAlgorithm, type DistanceOptions, type KeyName, type Match, type MatchOptions, type NormalizeOptions, type Rating, type SimilarityOptions, algorithms, bestMatch, compareTwoStrings, stringSimilarity as default, distance, findBestMatch, graphemes, normalize, rank, similarity };
package/dist/index.js ADDED
@@ -0,0 +1,3 @@
1
+ var J=/\s+/g;function U(e,t){if(e=e.replace(J,""),t=t.replace(J,""),e===t)return 1;let n=e.length,r=t.length;if(n<2||r<2)return 0;let o=new Map;for(let s=0;s<n-1;s++){let a=e.charCodeAt(s)*65536+e.charCodeAt(s+1);o.set(a,(o.get(a)??0)+1)}let i=0;for(let s=0;s<r-1;s++){let a=t.charCodeAt(s)*65536+t.charCodeAt(s+1),l=o.get(a);l&&(o.set(a,l-1),i++)}return 2*i/(n+r-2)}function j(e,t){if(!ae(e,t))throw new Error("Bad arguments: First argument should be a string, second should be an array of strings");let n=[],r=0;for(let i=0;i<t.length;i++){let s=t[i],a=U(e,s);n.push({target:s,rating:a}),a>n[r].rating&&(r=i)}let o=n[r];return{ratings:n,bestMatch:o,bestMatchIndex:r}}function ae(e,t){return!(typeof e!="string"||!Array.isArray(t)||!t.length||t.find(n=>typeof n!="string"))}function Q(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function N(e,t,n=1/0){if(e.length>t.length){let a=e;e=t,t=a}let r=e.length,o=t.length;if(o-r>n)return n+1;let i=0;for(;i<r&&e[i]===t[i];)i++;for(;r>i&&e[r-1]===t[o-1];)r--,o--;if(r-=i,o-=i,r===0)return o>n?n+1:o;let s=2*n+1<Math.ceil(r/32)*4?le(e,t,i,r,o,n):ce(e,t,i,r,o,n);return s>n?n+1:s}var I=new Uint32Array(64);function le(e,t,n,r,o,i){if(r===0)return o;I.length<r+1&&(I=new Uint32Array(Math.max(r+1,I.length*2)));let s=I;for(let l=0;l<=r;l++)s[l]=l;let a=i;for(let l=1;l<=o;l++){let c=t[n+l-1],g=l-a>1?l-a:1,u=l+a<r?l+a:r,d,h;g===1?(d=l-1,h=l,s[0]=l):(d=s[g-1],h=i+1);let m=h;for(let f=g;f<=u;f++){let y=s[f],p=e[n+f-1]===c?d:d+1;y+1<p&&(p=y+1),h+1<p&&(p=h+1),s[f]=p,d=y,h=p,p<m&&(m=p)}if(m>i)return i+1}return s[r]}var k=new Int32Array(65536),v=new Map,O=new Int8Array(64);function ce(e,t,n,r,o,i){if(r===0)return o;O.length<o&&(O=new Int8Array(Math.max(o,O.length*2)));let s=O;s.fill(1,0,o);let a=0;for(let l=0;l<r;l+=32){let c=Math.min(32,r-l),g=1<<c-1;for(let m=0;m<c;m++){let f=e[n+l+m];f<65536?k[f]=k[f]|1<<m:v.set(f,(v.get(f)??0)|1<<m)}let u=-1,d=0;a=l+c;let h=c===r;for(let m=0;m<o;m++){let f=t[n+m],y=f<65536?k[f]:v.get(f)??0,p=s[m],M=p>0?1:0,K=p<0?1:0,F=y|d,_=y|K,H=(_&u)+u^u|_,T=d|~(H|u),S=u&H;if(T&g?(s[m]=1,a++):S&g?(s[m]=-1,a--):s[m]=0,T=T<<1|M,S=S<<1|K,u=S|~(F|T),d=T&F,h&&a-(o-m-1)>i){a=i+1;break}}for(let m=0;m<c;m++){let f=e[n+l+m];f<65536?k[f]=0:v.delete(f)}}return a}function R(e,t,n=1/0){if(e.length>t.length){let c=e;e=t,t=c}let r=e.length,o=t.length;if(o-r>n)return n+1;if(r===0)return o>n?n+1:o;let i=new Uint32Array(r+1),s=new Uint32Array(r+1),a=new Uint32Array(r+1);for(let c=0;c<=r;c++)s[c]=c;for(let c=1;c<=o;c++){let g=t[c-1];a[0]=c;let u=c;for(let h=1;h<=r;h++){let m=e[h-1],f=s[h-1]+(m===g?0:1),y=s[h]+1,p=a[h-1]+1;if(y<f&&(f=y),p<f&&(f=p),h>1&&c>1&&m===t[c-2]&&e[h-2]===g){let M=i[h-2]+1;M<f&&(f=M)}a[h]=f,f<u&&(u=f)}if(u>n)return n+1;let d=i;i=s,s=a,a=d}let l=s[r];return l>n?n+1:l}function z(e,t){if(e.length!==t.length)throw new RangeError(`similarly: hamming needs two strings of the same length, got ${e.length} and ${t.length} characters`);let n=0;for(let r=0;r<e.length;r++)e[r]!==t[r]&&n++;return n}function $(e,t){if(e.length<t.length){let a=e;e=t,t=a}let n=e.length,r=t.length,o=0;for(;o<r&&e[o]===t[o];)o++;let i=o;for(;r>o&&e[n-1]===t[r-1];)n--,r--,i++;if(n-=o,r-=o,r===0)return i;let s=new Uint32Array(r+1);for(let a=0;a<n;a++){let l=e[o+a],c=0;for(let g=0;g<r;g++){let u=s[g+1];l===t[o+g]?s[g+1]=c+1:s[g]>u&&(s[g+1]=s[g]),c=u}}return i+s[r]}function ue(e,t){if(e.length!==t.length)return e.length-t.length;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return e[n]-t[n];return 0}function D(e,t){if(ue(e,t)>0){let u=e;e=t,t=u}let n=e.length,r=t.length;if(n===0||r===0)return n===r?1:0;let o=Math.max(0,Math.floor(Math.max(n,r)/2)-1),i=new Uint8Array(n),s=new Uint8Array(r),a=0;for(let u=0;u<n;u++){let d=Math.max(0,u-o),h=Math.min(r-1,u+o);for(let m=d;m<=h;m++)if(!s[m]&&e[u]===t[m]){i[u]=1,s[m]=1,a++;break}}if(a===0)return 0;let l=0,c=0;for(let u=0;u<n;u++)if(i[u]){for(;!s[c];)c++;e[u]!==t[c]&&l++,c++}let g=Math.floor(l/2);return(a/n+a/r+(a-g)/a)/3}function X(e,t,n,r,o){let i=D(e,t);if(i<=o)return i;let s=Math.min(r,e.length,t.length),a=0;for(;a<s&&e[a]===t[a];)a++;return Math.min(1,i+a*n*(1-i))}var E=2097152;function V(e,t,n){let r=e.length-t+1,o=new Array(Math.max(0,r));for(let i=0;i<r;i++)if(t===1)o[i]=e[i];else if(t===2&&n)o[i]=e[i]*E+e[i+1];else{let s=String(e[i]);for(let a=1;a<t;a++)s+=","+e[i+a];o[i]=s}return o}function Y(e){let t=0;for(let n=0;n<e.length;n++)e[n]>t&&(t=e[n]);return t}function B(e,t,n){let r=n!==2||Y(e)<E&&Y(t)<E,o=new Map;for(let i of V(e,n,r))o.set(i,(o.get(i)??0)+1);return[o,V(t,n,r)]}function Z(e,t,n){if(e.length<n||t.length<n)return 0;let[r,o]=B(e,t,n),i=0;for(let s of o){let a=r.get(s);a&&(r.set(s,a-1),i++)}return 2*i/(e.length-n+1+(t.length-n+1))}function ee(e,t,n){if(e.length<n||t.length<n)return 0;let[r,o]=B(e,t,n),i=0;for(let a of o){let l=r.get(a);l&&(r.set(a,l-1),i++)}let s=e.length-n+1+(t.length-n+1);return i/(s-i)}function te(e,t,n){if(e.length<n||t.length<n)return 0;let[r,o]=B(e,t,n),i=new Map;for(let c of o)i.set(c,(i.get(c)??0)+1);let s=0,a=0,l=0;for(let[c,g]of r){a+=g*g;let u=i.get(c);u&&(s+=g*u)}for(let c of i.values())l+=c*c;return Math.min(1,s/Math.sqrt(a*l))}var me=/\s+/g,ge=/\p{P}+/gu,fe=/[̀-ͯ᪰-᫿᷀-᷿⃐-⃿︠-︯]/g,P=/^[\u0000-˿]*$/,he=/[^\u0000-\u007f]/;function pe(e,t={}){return b(e,"text"),L(e,t??{})}function L(e,t){let n=P.test(e)?e:e.normalize("NFC");return t.caseSensitive||(n=n.toLowerCase()),t.ignoreAccents&&he.test(n)&&(n=n.normalize("NFKD").replace(fe,"").normalize("NFC")),t.ignorePunctuation&&(n=n.replace(ge,"")),t.ignoreWhitespace&&(n=n.replace(me,"")),n}var C;function ne(){if(C===void 0){let e=globalThis.Intl?.Segmenter;C=typeof e=="function"?new e(void 0,{granularity:"grapheme"}):null}return C}var de=/\r\n|\p{Regional_Indicator}{2}|[^\p{M}‍](?:‍\p{Extended_Pictographic}|[्্્୍్്]‍?\p{L}|[\p{M}‌‍︎️\u{1f3fb}-\u{1f3ff}\u{e0020}-\u{e007f}])*|[\s\S]/gu;function re(e){return e.match(de)??[]}function ye(e){if(b(e,"text"),P.test(e)&&e.indexOf(`\r
2
+ `)===-1)return e.split("");let t=ne();if(!t)return re(e);let n=[];for(let r of t.segment(e))n.push(r.segment);return n}var x=class{constructor(){this.next=65536}id(t){if(t.length===1)return t.charCodeAt(0);let n=this.ids??(this.ids=new Map),r=n.get(t);return r===void 0&&(r=this.next++,n.set(t,r)),r}};function ie(e,t,n){if(!t||P.test(e)&&e.indexOf(`\r
3
+ `)===-1){let s=new Int32Array(e.length);for(let a=0;a<e.length;a++)s[a]=e.charCodeAt(a);return s}let r=ne(),o=r?r.segment(e):re(e),i=[];for(let s of o)i.push(n.id(typeof s=="string"?s:s.segment));return Int32Array.from(i)}function b(e,t){if(typeof e!="string")throw new TypeError(`similarly: ${t} must be a string, got ${w(e)}`)}function w(e){if(e===null)return"null";if(Array.isArray(e))return"an array";let t=typeof e;return t==="object"?"an object":t==="undefined"?"undefined":`a ${t}`}var G=Object.freeze(["dice","levenshtein","damerauLevenshtein","jaro","jaroWinkler","jaccard","cosine","lcs","hamming"]),oe=["levenshtein","damerauLevenshtein","hamming","lcs"];function be(e){return typeof e=="string"&&G.includes(e)}function W(e){let t=e??{},n=t.algorithm??"dice";if(!be(n))throw new RangeError(`similarly: unknown algorithm ${JSON.stringify(n)}. Use one of: ${G.join(", ")}`);let r=t.n??2;if(!Number.isInteger(r)||r<1)throw new RangeError(`similarly: n must be a whole number of 1 or more, got ${String(r)}`);let o=t.prefixScale??.1,i=t.maxPrefix??4,s=t.boostThreshold??.7;if(!Number.isInteger(i)||i<0)throw new RangeError(`similarly: maxPrefix must be a whole number of 0 or more, got ${String(i)}`);if(typeof o!="number"||!(o>=0)||o*i>1)throw new RangeError(`similarly: prefixScale must be 0 or more, and prefixScale * maxPrefix must be 1 or less, got ${String(o)}`);if(typeof s!="number"||!(s>=0&&s<=1))throw new RangeError(`similarly: boostThreshold must be from 0 to 1, got ${String(s)}`);return{algorithm:n,normalize:t,graphemes:t.graphemes??!0,n:r,prefixScale:o,maxPrefix:i,boostThreshold:s}}function A(e,t,n){return ie(L(e,t.normalize),t.graphemes,n)}function q(e,t,n){if(n.algorithm==="hamming"){let r=z(e,t);return e.length===0?1:1-r/e.length}if(Q(e,t))return 1;switch(n.algorithm){case"dice":return Z(e,t,n.n);case"jaccard":return ee(e,t,n.n);case"cosine":return te(e,t,n.n);case"levenshtein":return 1-N(e,t)/Math.max(e.length,t.length);case"damerauLevenshtein":return 1-R(e,t)/Math.max(e.length,t.length);case"jaro":return D(e,t);case"jaroWinkler":return X(e,t,n.prefixScale,n.maxPrefix,n.boostThreshold);case"lcs":return 2*$(e,t)/(e.length+t.length)}}function we(e,t,n){b(e,"the first argument"),b(t,"the second argument");let r=W(n),o=new x;return q(A(e,r,o),A(t,r,o),r)}function xe(e,t,n){b(e,"the first argument"),b(t,"the second argument");let r=n??{},o=r.algorithm??"levenshtein";if(!oe.includes(o))throw new RangeError(`similarly: distance() supports ${oe.join(", ")}, got ${typeof o=="string"?JSON.stringify(o):w(o)}. Use similarity() for the others`);let i=r.maxDistance??1/0;if(!(Number.isInteger(i)||i===1/0)||i<0)throw new RangeError(`similarly: maxDistance must be a whole number of 0 or more, got ${String(i)}`);let s=new x,a={normalize:r,graphemes:r.graphemes??!0},l=A(e,a,s),c=A(t,a,s),g;switch(o){case"levenshtein":return N(l,c,i);case"damerauLevenshtein":return R(l,c,i);case"hamming":g=z(l,c);break;case"lcs":if(Math.abs(l.length-c.length)>i)return i+1;g=l.length+c.length-2*$(l,c);break}return g>i?i+1:g}function Ae(e){if(e===void 0)return(n,r)=>{if(typeof n!="string")throw new TypeError(`similarly: candidate at index ${r} is ${w(n)}, not a string. Use the key option to compare objects`);return n};let t=typeof e=="function"?e:typeof e=="string"?n=>n?.[e]:(()=>{throw new TypeError(`similarly: key must be a property name or a function, got ${w(e)}`)})();return(n,r)=>{let o=t(n,r);if(o!=null){if(typeof o!="string")throw new TypeError(`similarly: key value at index ${r} is ${w(o)}, not a string`);return o}}}function se(e,t,n){if(b(e,"the query"),!Array.isArray(t))throw new TypeError(`similarly: candidates must be an array, got ${w(t)}`);let r=n??{},o=W(r),i=r.threshold??0;if(typeof i!="number"||!(i>=0&&i<=1))throw new RangeError(`similarly: threshold must be from 0 to 1, got ${String(i)}`);let s=r.limit??1/0;if(!(Number.isInteger(s)||s===1/0)||s<0)throw new RangeError(`similarly: limit must be a whole number of 0 or more, got ${String(s)}`);let a=new x,l=A(e,o,a);return{query:l,get:Ae(r.key),threshold:i,limit:s,each:c=>q(l,A(c,o,a),o)}}function Te(e,t,n){let r=se(e,t,n),o=[];if(r.limit===0)return o;for(let i=0;i<t.length;i++){let s=t[i],a=r.get(s,i);if(a===void 0)continue;let l=r.each(a);l>=r.threshold&&o.push({item:s,target:a,rating:l,index:i})}return o.sort((i,s)=>s.rating-i.rating),o.length>r.limit&&(o.length=r.limit),o}function Me(e,t,n){let r=se(e,t,n),o;if(r.limit===0)return o;for(let i=0;i<t.length;i++){let s=t[i],a=r.get(s,i);if(a===void 0)continue;let l=r.each(a);l>=r.threshold&&(o===void 0||l>o.rating)&&(o={item:s,target:a,rating:l,index:i})}return o}var Se={compareTwoStrings:U,findBestMatch:j},$e=Se;export{G as algorithms,Me as bestMatch,U as compareTwoStrings,$e as default,xe as distance,j as findBestMatch,ye as graphemes,pe as normalize,Te as rank,we as similarity};
package/package.json CHANGED
@@ -1,6 +1,75 @@
1
1
  {
2
2
  "name": "similarly",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0",
4
+ "description": "Compare how similar two strings are and find the best match in a list. Drop-in replacement for the deprecated string-similarity, with TypeScript types, Levenshtein, Jaro-Winkler and more. Zero dependencies.",
5
+ "keywords": [
6
+ "string-similarity",
7
+ "similarity",
8
+ "string-compare",
9
+ "fuzzy",
10
+ "fuzzy-match",
11
+ "fuzzy-search",
12
+ "best-match",
13
+ "dice-coefficient",
14
+ "levenshtein",
15
+ "damerau-levenshtein",
16
+ "edit-distance",
17
+ "jaro-winkler",
18
+ "jaro",
19
+ "jaccard",
20
+ "cosine-similarity",
21
+ "hamming",
22
+ "lcs",
23
+ "grapheme",
24
+ "typescript"
25
+ ],
26
+ "license": "MIT",
27
+ "author": "CK Giri <ckgdev@gmail.com>",
28
+ "funding": "https://github.com/ckgiri/similarly?sponsor=1",
29
+ "homepage": "https://github.com/ckgiri/similarly",
30
+ "repository": {
31
+ "type": "git",
32
+ "url": "git+https://github.com/ckgiri/similarly.git"
33
+ },
34
+ "bugs": {
35
+ "url": "https://github.com/ckgiri/similarly/issues"
36
+ },
37
+ "type": "module",
38
+ "sideEffects": false,
39
+ "main": "./dist/index.cjs",
40
+ "module": "./dist/index.js",
41
+ "types": "./dist/index.d.ts",
42
+ "exports": {
43
+ ".": {
44
+ "import": {
45
+ "types": "./dist/index.d.ts",
46
+ "default": "./dist/index.js"
47
+ },
48
+ "require": {
49
+ "types": "./dist/index.d.cts",
50
+ "default": "./dist/index.cjs"
51
+ }
52
+ },
53
+ "./package.json": "./package.json"
54
+ },
55
+ "files": [
56
+ "dist",
57
+ "CHANGELOG.md"
58
+ ],
59
+ "engines": {
60
+ "node": ">=20"
61
+ },
62
+ "scripts": {
63
+ "build": "tsup",
64
+ "test": "vitest run",
65
+ "typecheck": "tsc -p .",
66
+ "prepublishOnly": "npm run typecheck && npm run build && npm test"
67
+ },
68
+ "devDependencies": {
69
+ "@types/node": "^20.14.0",
70
+ "string-similarity": "^4.0.4",
71
+ "tsup": "^8.3.0",
72
+ "typescript": "^5.6.0",
73
+ "vitest": "^2.1.0"
74
+ }
75
+ }