Skip to content
/ kmps Public

Knuth–Morris–Pratt algorithm that works with JS Array & TypedArray

License

Notifications You must be signed in to change notification settings

Chocobo1/kmps

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

8 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Knuth–Morris–Pratt Search

An naive implementation of Knuth–Morris–Pratt algorithm that works with Array & TypedArray

Installation

npm install git+https://github.com/Chocobo1/kmps.git

Usage example

const Kmp = require('kmps');  // import this module, CommonJS style
//import * as Kmp from 'kmps';  // import this module, ES module style

// working with TypedArray
{
    const pattern = Uint32Array.from([0xFFFF, 0x3000]);
    const corpus = Uint32Array.from([0xFFFF, 0xFFFF, 0x3000, 0x1000]);

    // setup `kmp` for later reuse
    const kmp = Kmp.KnuthMorrisPratt(pattern);
    // returns the first index of the exact match in `corpus`; -1 if not found
    const idx = kmp.match(corpus);
    if (idx !== 1)
        throw (new Error('Please file an issue'));
}

// also working with String
{
    const pattern = "pattern";
    const corpus = "some pattern !@#$%";

    const kmp = Kmp.KnuthMorrisPratt(pattern);
    const idx = kmp.match(corpus);
    if (idx !== corpus.indexOf(pattern))
        throw (new Error('Please file an issue'));
}

// you can specify offset!
{
    const pattern = "123";
    const corpus = "123abc123";
    const corpusOffset = 1;

    const idx = Kmp.KnuthMorrisPratt(pattern).match(corpus, corpusOffset);
    if (idx !== corpus.indexOf(pattern, corpusOffset))
        throw (new Error('Please file an issue'));
}

Run tests

npm install -D  # install dev dependencies
npm test        # run tests

References

See also

You might be interested to Boyer–Moore–Horspool algorithm

License

See LICENSE file

About

Knuth–Morris–Pratt algorithm that works with JS Array & TypedArray

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published