npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

symspell-ex

v1.1.10

Published

Spelling correction & Fuzzy search based on symmetric delete spelling correction algorithm

Downloads

1,837

Readme

SymSpellEx

Spelling correction & Fuzzy search based on Symmetric Delete Spelling Correction algorithm (SymSpell)

Work in progress, need more optimizations

Node Version npm version Build Status Coverage Status License

Installation

npm install symspell-ex --save

Changes v1.1.1

  • Tokenization support
  • Term frequency should be provided for training and terms should be unique
  • Correct function return different object (Correction object)
  • Hash table implemented in redis store instead of normal list structure
  • Enhanced testing code and coverage
  • Fixed bugs in lookup

Features

  • Very fast
  • Word suggestions
  • Word correction
  • Multiple languages supported - The algorithm, and the implementation are language independent
  • Extendable - Edit distance and data stores can be implemented to extend library functionalities

Usage

Training

For single term training you can use add function:

import {SymSpellEx, MemoryStore} from 'symspell-ex';

const LANGUAGE = 'en';
// Create SymSpellEx instnce and inject store new store instance
symSpellEx = new SymSpellEx(new MemoryStore());
await symSpellEx.initialize();
// Train data
await symSpellEx.add("argument", LANGUAGE);
await symSpellEx.add("computer", LANGUAGE);

For multiple terms (Array) you can use train function:

const terms = ['argument', 'computer'];
await symSpellEx.train(terms, 1, LANGUAGE);

Searching

search function can be used to get multiple suggestions if available up to the maxSuggestions value

Arguments:

  • input String (Wrong/Invalid word we need to correct)
  • language String (Language to be used in search)
  • maxDistance Number, optional, default = 2 (Maximum distance for suggestions)
  • maxSuggestions Number, optional, default = 5 (Maximum suggestions number to return)

Return: Array<Suggetion> Array of suggestions

Example

await symSpellEx.search('argoments', 'en');

Example Suggestion Object:

{
  "term": "argoments",
  "suggestion": "arguments",  
  "distance": 2,
  "frequency": 155
}

Correction

correct function can be used to get the best suggestion for input word or sentence in terms of edit distance and frequency

Arguments:

  • input String (Wrong/Invalid word we need to correct)
  • language String (Language to be used in search)
  • maxDistance Number, optional, default = 2 (Maximum distance for suggestions)

Return: Correction object which contains original input and corrected output string, with array of suggestions

Example

await symSpellEx.correct('Special relatvity was orignally proposed by Albert Einstein', 'en');

Returns this Correction object:

This output is totally depending on the quality of the training data that was push into the store

{
  "suggestions": [],
  "input": "Special relatvity was orignally proposed by Albert Einstein",
  "output": "Special relativity was originally proposed by Albert Einstein"
}

Computational Complexity

The algorithm has constant time O(1) time, independent of the dictionary size, but depend on the average term length and maximum edit distance, Hash Table is used to store all search entries which has an average search time complexity of O(1).

Why the algorithm is fast?

Pre-calculation

in training phase all possible spelling error variants as generated (deletes only) and stored in hash table

This makes the algorithm very fast, but it also required a large memory footprint, and the training phase takes a considerable amount of time to build the dictionary first time. (Using RedisStore makes it easy to train and build once, then search and correct from any external source)

Symmetric Delete Spelling Correction

It allows a tremendous reduction of the number of spelling error candidates to be pre-calculated (generated and added to hash table), which then allows O(1) search while getting spelling suggestions.

Library Design

Lib Diagram

Tokenizer

This interface can be implemented to provide a different tokenizer for the library

Interface type

export interface Tokenizer {
    tokenize(input: string): Array<Token>;
}

EditDistance

This interface can be implemented to provide more algorithms to use to calculate edit distance between two words

Edit Distance is a way of quantifying how dissimilar two strings (e.g., words) are to one another by counting the minimum number of operations required to transform one string into the other

Interface type

interface EditDistance {
    name: String;
    calculateDistance(source: string, target: string): number;
}

DataStore

This interface can be implemented to provide additional method to store data other than built-in stores (Memory, Redis)

Data store should handle storage for these 2 data types:

  • Terms: List data structure to store terms and retrieve it by index
  • Entries: Hash Table data structure to store dictionary entries and retrieve data by term (Key)

Data store should also handle storage for multiple languages and switch between them

Interface type

export interface DataStore {
    name: string;
    initialize(): Promise<void>;
    isInitialized(): boolean;
    setLanguage(language: string): Promise<void>;
    pushTerm(value: string): Promise<number>;
    getTermAt(index: number): Promise<string>;
    getTermsAt(indexes: Array<number>): Promise<Array<string>>;
    getEntry(key: string): Promise<Array<number>>;
    getEntries(keys: Array<string>): Promise<Array<Array<number>>>;
    setEntry(key: string, value: Array<number>): Promise<boolean>;
    hasEntry(key: string): Promise<boolean>;
    maxEntryLength(): Promise<number>;
    clear(): Promise<void>;
}

Built-in data stores

  • Memory: Stores data in memory, using array structure for terms and high speed hash table (megahash) to manage dictionary entries

May be limited by node process memory limits, which can be overridden

  • Redis: Stores data into Redis database using list structure to store terms and hash to store dictionary data

Very efficient way to train and store data, it will allow accessing by multiple processes and/or machines, also dumping and migrating data will be easy

TODO

  • [x] Tokenization
  • [x] Sentence correction
  • [x] Bulk data training
  • [ ] Word Segmentation
  • [ ] Domain specific correction

References

License

MIT