Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add similarity function #122

Merged
merged 2 commits into from
Jul 23, 2024
Merged

feat: add similarity function #122

merged 2 commits into from
Jul 23, 2024

Conversation

aleclarson
Copy link
Member

@aleclarson aleclarson commented Jul 18, 2024

Tip

The owner of this PR can publish a preview release by commenting /publish in this PR. Afterwards, anyone can try it out by running pnpm add radashi@pr<PR_NUMBER>.

Summary

This function calculates the “Levenshtein distance” between two strings, which is a fancy way of saying how many characters did not match. Note that it's case-sensitive.

// Order of arguments has no effect.
similarity('ababab', 'ab') // 4
similarity('ab', 'ababab') // 4

// Exact matches return zero.
similarity('a', 'b') // 1
similarity('a', 'a') // 0

Its most common use case is in quick and dirty “fuzzy matching” solutions. By passing the search query as one argument and the possible match as the other argument, you can score each possible match to determine which is most similar to the search query.

const possibleMatches = ['Apple', 'Pineapple', 'Grapes']
const searchQuery = 'App'

const [bestMatch] = possibleMatches.reduce(
  (best, possibleMatch) => {
    const score = _.similarity(searchQuery, possibleMatch)
    if (score < best[1]) {
      best[0] = possibleMatch
      best[1] = score
    }
    return best
  },
  [undefined, Number.POSITIVE_INFINITY] as const,
)

For any code change,

  • Related documentation has been updated, if needed
  • Related tests have been added or updated, if needed
  • Related benchmarks have been added or updated, if needed

Does this PR introduce a breaking change?

No

Bundle impact

Status File Size
A src/string/similarity.ts 455 1

Footnotes

  1. Function size includes the import dependencies of the function.

@aleclarson aleclarson mentioned this pull request Jul 18, 2024
3 tasks
@aleclarson aleclarson force-pushed the feat/similarity-fn branch from b8a2b69 to 20eb6f6 Compare July 23, 2024 15:51
@aleclarson aleclarson marked this pull request as ready for review July 23, 2024 16:10
@aleclarson aleclarson merged commit dac01cc into main Jul 23, 2024
7 of 8 checks passed
@aleclarson aleclarson deleted the feat/similarity-fn branch July 23, 2024 16:51
Copy link

A new beta version 12.2.0-beta.83909af has been published to NPM. 🚀

To install:

The radashi@beta tag also includes this PR.

See the changes

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant