Skip to content

Commit

Permalink
refactor: prepare FuzzySort for multiple data under the same key
Browse files Browse the repository at this point in the history
  • Loading branch information
marcelgerber committed Mar 3, 2025
1 parent 6b5dc15 commit f7ba408
Showing 1 changed file with 4 additions and 4 deletions.
8 changes: 4 additions & 4 deletions packages/@ourworldindata/utils/src/FuzzySearch.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,21 @@
import { keyBy } from "./Util.js"
import { groupBy } from "./Util.js"
import fuzzysort from "fuzzysort"

export class FuzzySearch<T> {
strings: Fuzzysort.Prepared[]
datamap: Record<string, T>
datamap: Record<string, T[]>
opts: Fuzzysort.Options | undefined

constructor(data: T[], key: keyof T, opts?: Fuzzysort.Options) {
this.datamap = keyBy(data, key)
this.datamap = groupBy(data, key)
this.strings = data.map((d) => fuzzysort.prepare(d[key] as string))
this.opts = opts
}

search(input: string): T[] {
return fuzzysort
.go(input, this.strings, this.opts)
.map((result) => this.datamap[result.target])
.flatMap((result) => this.datamap[result.target])
}

searchResults(input: string): Fuzzysort.Results {
Expand Down

0 comments on commit f7ba408

Please sign in to comment.