Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

1.3 KB
Raw Blame
import FuseClass, { FuseResultMatch, IFuseOptions } from 'fuse.js'

export type Fuse<T> = FuseClass<T>
export type { FuseResultMatch, IFuseOptions }

const FUSE_DEFAULTS = {
    threshold: 0.3,
    ignoreDiacritics: true,
}

export function createFuse<T>(items: T[], options: IFuseOptions<T>): FuseClass<T> {
    return new FuseClass<T>(items, { ...FUSE_DEFAULTS, ...options } as IFuseOptions<T>)
}

export type FuseSearch<T> = (items: T[], term: string) => T[]

export function createFuseSearch<T>(keys: (keyof T & string)[]): FuseSearch<T> {
    const fuse = createFuse<T>([], { keys })
    return (items: T[], term: string): T[] => {
        // Trim before searching: leading/trailing whitespace changes the pattern length
        // and inflates Fuse's effective edit budget (threshold × length), which lets
        // unrelated items match (e.g. "mcp " picks up "Map clicked", "SMTP delivered").
        const trimmed = term.trim()
        if (!trimmed) {
            return items
        }
        fuse.setCollection(items)
        return fuse.search(trimmed).map((r) => r.item)
    }
}

export function createFeaturePreviewSearch<
    T extends { name: string; description: string; stage: string },
>(): FuseSearch<T> {
    return createFuseSearch<T>(['name', 'description', 'stage'])
}