All files / owid-grapher/grapher/controls FuzzySearch.ts

48.65% Statements 18/37
100% Branches 0/0
0% Functions 0/5
48.65% Lines 18/37

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 361x 1x 1x 1x 1x 1x 1x 1x       1x 1x         1x 1x     1x 1x       1x 1x               1x
import { keyBy } from "../../clientUtils/Util"
import fuzzysort from "fuzzysort"
 
export class FuzzySearch<T> {
    strings: (Fuzzysort.Prepared | undefined)[]
    datamap: any
 
    constructor(data: T[], key: string) {
        this.datamap = keyBy(data, key)
        this.strings = data.map((d: any) => fuzzysort.prepare(d[key]))
    }
 
    search(input: string): T[] {
        return fuzzysort
            .go(input, this.strings)
            .map((result: any) => this.datamap[result.target])
    }
 
    single(input: string, target: string): Fuzzysort.Result | null {
        return fuzzysort.single(input, target)
    }
 
    highlight(input: string, target: string): string {
        const result = fuzzysort.single(input, target)
        return highlight(result) ?? target
    }
}
 
export function highlight(result: Fuzzysort.Result | null): string | null {
    // The type definition of fuzzysort.highlight is wrong: It won't accept `undefined` as input,
    // but will happily accept `null`. That's why we use this wrapper here so we can actually call it.
    // Don't call fuzzysort.highlight directly if the value can be null or undefined, since one will
    // result in a type error and the other in a runtime error!
    return fuzzysort.highlight(result!)
}