fuzzysort

repository·master·Indexed 23 days ago

https://github.com/farzher/fuzzysort

A fast, lightweight (5kb), and zero-dependency fuzzy search library for JavaScript, version 3.1.0. It provides SublimeText-like search capabilities for strings and objects via the `fuzzysort.go()` API. Features include support for multiple search keys, custom scoring functions, result highlighting, and performance optimizations using `fuzzysort.prepare()` for pre-calculating targets.

Tokens
2.2K
Snippets
8
Records
14
Agent score
38%

What's inside fuzzysort

  1. Install fuzzysort via npm, Bun, or Deno

    master

    To use fuzzysort in a Node.js, Bun, or Deno environment, install it using your package manager and import it into your project.

    npm i fuzzysort
    import fuzzysort from 'fuzzysort'
    // or
    const fuzzysort = require('fuzzysort')
  2. Optimize fuzzysort performance

    master

    To achieve maximum performance:

    1. Filter targets: Remove long strings or unnecessary objects before searching.
    2. Use fuzzysort.prepare(): If targets don't change often, pre-calculate prepared targets.
    3. Avoid options.key: If you don't need a reference to the original object, search against prepared strings directly.
    4. Set limits: Use options.limit and options.threshold to reduce the amount of work.
    let targets = [{file: 'Monitor.cpp'}, {file: 'MeshRenderer.cpp'}]
    
    // 1. Filter
    targets = targets.filter(t => t.file.length < 1000)
    
    // 2. Prepare
    targets.forEach(t => t.filePrepared = fuzzysort.prepare(t.file))
    
    // 3. Search prepared strings directly (avoids options.key overhead)
    targets = targets.map(t => t.filePrepared)
    
    const options = {
      limit: 100,
      threshold: .5,
    }
    fuzzysort.go('fast', targets, options)
  3. Configure fuzzysort.go() options

    master

    The options object in fuzzysort.go allows you to fine-tune search behavior:

    • threshold: (number) Don't return matches worse than this.
    • limit: (number) Don't return more results than this.
    • all: (boolean) If true, returns all results for an empty search.
    • key: (string|function) For when targets are objects. Can be a property name or a function.
    • keys: (array) For searching multiple keys in objects.
    • scoreFn: (function) Custom scoring function used when keys is provided.
    fuzzysort.go(search, targets, {
      threshold: 0,
      limit: 0,
      all: false,
      key: null,
      keys: null,
      scoreFn: null,
    })
  4. Note on result.score precision

    master

    Because result.score is implemented as a getter/setter, it may exhibit floating-point precision artifacts when manually assigned.

    Example: r.score = .3; might result in r.score == 0.30000000000000004.

  5. Search objects with multiple keys and custom weights

    master

    You can search through an array of objects by providing an array of keys to options.keys. You can also use options.scoreFn to boost or penalize specific results based on object properties.

    let objects = [{
      title: 'Liechi Berry',
      meta: {desc: 'Raises Attack when HP is low.'},
      tags: ['berries', 'items'],
      bookmarked: true,
    }, {
      title: 'Petaya Berry',
      meta: {desc: 'Raises Special Attack when HP is low.'},
    }]
    
    let results = fuzzysort.go('attack berry', objects, {
      keys: ['title', 'meta.desc', obj => obj.tags?.join()],
      scoreFn: r => r.score * r.obj.bookmarked ? 2 : 1, // if the item is bookmarked, boost its score
    })
    
    var keysResult = results[0]
    // When using multiple `keys`, results are different. They're indexable to get each normal result
    keysResult[0].highlight() // 'Liechi <b>Berry</b>'
    keysResult[1].highlight() // 'Raises <b>Attack</b> when HP is low.'
    keysResult.score          // .84
    keysResult.obj.title      // 'Liechi Berry'
  6. Perform a fuzzy search with fuzzysort.go()

    master

    Use fuzzysort.go(search, targets, options) to perform a fuzzy search. If targets is an array of objects, use the key option to specify which property to search.

    const mystuff = [{file: 'Apple.cpp'}, {file: 'Banana.cpp'}]
    const results = fuzzysort.go('a', mystuff, {key: 'file'})
    // [{score: 0.81, obj: {file: 'Apple.cpp'}}, {score: 0.59, obj: {file: 'Banana.cpp'}}]
  7. Access search result properties

    master

    A search result object contains metadata about the match. When using options.key, the obj property provides a reference to your original object.

    const result = fuzzysort.single('query', 'some string that contains my query.')
    result.score       // .80 (1 is a perfect match. 0.5 is a good match. 0 is no match.)
    result.target      // 'some string that contains my query.'
    result.obj         // reference to your original obj when using options.key
    result.indexes     // [29, 30, 31, 32, 33]
  8. Highlight search matches in results

    master

    Use the highlight method on a result object to wrap matching characters in HTML tags or to use a custom callback (e.g., for React components).

    // HTML highlighting
    result.highlight('<b>', '</b>')
    // 'some string that contains my <b>query</b>.'
    
    // Custom callback (e.g. React)
    result.highlight((m, i) => <react key={i}>{m}</react>)
    // ['some string that contains my ', <react key=0>query</react>, '.']
  9. Highlight search matches in a result

    master

    Each result returned by fuzzysort.go() (of type Result) has a .highlight(open, close) method. This method wraps the matching characters in the target string with the provided tags or uses a callback function.

    • open: A string (e.g., '<b>') or a function to handle the opening tag.
    • close: A string (e.g., '</b>') or a function to handle the closing tag.

    If a callback is provided, it is called for each match with the matched text and the match index.

  10. Perform fuzzy searching with fuzzysort.go()

    master

    The primary API for fuzzy searching is fuzzysort.go(search, targets, options). It allows you to search through an array of strings or an array of objects.

    • search: The string you are searching for.
    • targets: An array of strings or objects to search through.
    • options: An optional configuration object.

    If searching through objects, you must specify which property to search using options.key or multiple properties using options.keys.