CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-fuse-js

Lightweight fuzzy-search library with zero dependencies that implements efficient fuzzy string matching algorithms

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

index-management.mddocs/

Index Management

Pre-indexing system for optimizing search performance on large datasets. Includes index creation, serialization for caching, and methods for retrieving index information from Fuse instances.

Capabilities

Create Index

Pre-generates a search index for improved performance on large datasets or repeated searches.

/**
 * Pre-generates a search index for performance optimization
 * @param keys - Field keys to index
 * @param list - Data array to index
 * @param options - Index configuration options
 * @returns FuseIndex instance for use with Fuse constructor
 */
static createIndex<U>(
  keys: Array<FuseOptionKey<U>>,
  list: ReadonlyArray<U>,
  options?: FuseIndexOptions<U>
): FuseIndex<U>;

Usage Examples:

import Fuse from "fuse.js";

const books = [
  { title: "The Great Gatsby", author: "F. Scott Fitzgerald" },
  { title: "To Kill a Mockingbird", author: "Harper Lee" },
  // ... thousands more books
];

// Create index once for reuse
const index = Fuse.createIndex(["title", "author"], books);

// Use pre-built index for faster instantiation
const fuse = new Fuse(books, { keys: ["title", "author"] }, index);

// Advanced key configuration with index
const weightedIndex = Fuse.createIndex([
  { name: "title", weight: 2 },
  { name: "author", weight: 1 },
  { name: "isbn" }
], books);

Parse Index

Reconstructs a FuseIndex from serialized JSON data for index persistence and caching.

/**
 * Parses serialized index data back into FuseIndex instance
 * @param index - Serialized index data with keys and records
 * @param options - Index configuration options
 * @returns FuseIndex instance
 */
static parseIndex<U>(
  index: {
    keys: ReadonlyArray<string>;
    records: FuseIndexRecords;
  },
  options?: FuseIndexOptions<U>
): FuseIndex<U>;

Usage Examples:

// Serialize index for storage
const originalIndex = Fuse.createIndex(["title", "author"], books);
const serializedData = originalIndex.toJSON();

// Store in localStorage/database/file
localStorage.setItem("bookIndex", JSON.stringify(serializedData));

// Later, retrieve and reconstruct
const storedData = JSON.parse(localStorage.getItem("bookIndex"));
const reconstructedIndex = Fuse.parseIndex(storedData);

// Use reconstructed index
const fuse = new Fuse(books, { keys: ["title", "author"] }, reconstructedIndex);

Get Index

Retrieves the internal FuseIndex instance from a Fuse search engine.

/**
 * Returns the internal FuseIndex instance
 * @returns The current FuseIndex used by this Fuse instance
 */
getIndex(): FuseIndex<T>;

Usage Examples:

const fuse = new Fuse(books, { keys: ["title", "author"] });

// Get the internal index
const index = fuse.getIndex();

// Serialize for caching
const indexData = index.toJSON();
console.log("Index has", indexData.records.length, "records");

// Access index properties
console.log("Indexed keys:", indexData.keys);

FuseIndex Class

The FuseIndex class handles internal indexing operations and data structure management.

class FuseIndex<T> {
  /**
   * Creates a new FuseIndex instance
   * @param options - Index configuration options
   */
  constructor(options?: FuseIndexOptions<T>);
  
  /**
   * Sets the source documents for indexing
   * @param docs - Array of documents to index
   */
  setSources(docs: ReadonlyArray<T>): void;
  
  /**
   * Sets the keys (fields) to be indexed
   * @param keys - Array of key names to index
   */
  setKeys(keys: ReadonlyArray<string>): void;
  
  /**
   * Sets pre-computed index records
   * @param records - Index record data
   */
  setIndexRecords(records: FuseIndexRecords): void;
  
  /**
   * Creates the index from sources and keys
   */
  create(): void;
  
  /**
   * Adds a single document to the index
   * @param doc - Document to add
   */
  add(doc: T): void;
  
  /**
   * Serializes the index to JSON for storage
   * @returns Serializable index data
   */
  toJSON(): {
    keys: ReadonlyArray<string>;
    records: FuseIndexRecords;
  };
  
  /**
   * Returns the number of records in the index
   * @returns The size of the index
   */
  size(): number;
}

Usage Examples:

// Manual index creation
const index = new FuseIndex({
  getFn: (obj, path) => obj[path] // Custom getter function
});

index.setSources(books);
index.setKeys(["title", "author"]);
index.create();

// Add new document to existing index
index.add({ title: "New Book", author: "New Author" });

// Check index size
console.log(`Index contains ${index.size()} records`);

Index Configuration

Configuration options for controlling index behavior and value extraction.

interface FuseIndexOptions<T> {
  /** Custom function for extracting field values */
  getFn: FuseGetFunction<T>;
}

type FuseGetFunction<T> = (
  obj: T,
  path: string | string[]
) => ReadonlyArray<string> | string;

Usage Examples:

// Custom getter for complex data structures
const customIndex = Fuse.createIndex(
  ["searchableText"],
  products,
  {
    getFn: (product, path) => {
      if (path === "searchableText") {
        return [
          product.title,
          product.description,
          ...product.tags,
          product.category
        ].join(" ");
      }
      return product[path];
    }
  }
);

Index Record Types

Internal data structures used by the indexing system.

type FuseIndexRecords = 
  | ReadonlyArray<FuseIndexObjectRecord>
  | ReadonlyArray<FuseIndexStringRecord>;

interface FuseIndexObjectRecord {
  /** Original array index */
  i: number;
  /** Indexed field data */
  $: RecordEntry;
}

interface FuseIndexStringRecord {
  /** Original array index */
  i: number;
  /** String value */
  v: string;
  /** Field length normalization value */
  n: number;
}

type RecordEntry = {
  [key: string]: RecordEntryObject | RecordEntryArrayItem;
};

interface RecordEntryObject {
  /** Text value */
  v: string;
  /** Field length normalization value */
  n: number;
}

type RecordEntryArrayItem = ReadonlyArray<
  RecordEntryObject & { i: number }
>;

Index Performance Patterns

Best practices for optimal index usage and performance.

Usage Examples:

// For large, static datasets - create index once
const largeDataIndex = Fuse.createIndex(keys, largeDataset);
const fuse1 = new Fuse(largeDataset, options, largeDataIndex);
const fuse2 = new Fuse(largeDataset, differentOptions, largeDataIndex);

// For frequently recreated searches - serialize index
const indexData = largeDataIndex.toJSON();
// ... later
const restoredIndex = Fuse.parseIndex(indexData);

// For dynamic datasets - use collection management instead
const dynamicFuse = new Fuse(initialData, options);
dynamicFuse.add(newItem); // More efficient than recreating index

// Memory optimization - serialize and store large indices
if (dataset.length > 10000) {
  const index = Fuse.createIndex(keys, dataset);
  const serialized = JSON.stringify(index.toJSON());
  // Store serialized data, recreate index when needed
}

docs

collection-management.md

core-search.md

extended-search.md

index-management.md

index.md

tile.json