项目作者: Chocobo1

项目描述 :
Knuth–Morris–Pratt algorithm that works with JS Array & TypedArray
高级语言: JavaScript
项目地址: git://github.com/Chocobo1/kmps.git
创建时间: 2019-01-12T13:46:27Z
项目社区:https://github.com/Chocobo1/kmps

开源协议:BSD 3-Clause "New" or "Revised" License

下载


Knuth–Morris–Pratt Search

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

Installation

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

Usage example

  1. const Kmp = require('kmps'); // import this module, CommonJS style
  2. //import * as Kmp from 'kmps'; // import this module, ES module style
  3. // working with TypedArray
  4. {
  5. const pattern = Uint32Array.from([0xFFFF, 0x3000]);
  6. const corpus = Uint32Array.from([0xFFFF, 0xFFFF, 0x3000, 0x1000]);
  7. // setup `kmp` for later reuse
  8. const kmp = Kmp.KnuthMorrisPratt(pattern);
  9. // returns the first index of the exact match in `corpus`; -1 if not found
  10. const idx = kmp.match(corpus);
  11. if (idx !== 1)
  12. throw (new Error('Please file an issue'));
  13. }
  14. // also working with String
  15. {
  16. const pattern = "pattern";
  17. const corpus = "some pattern !@#$%";
  18. const kmp = Kmp.KnuthMorrisPratt(pattern);
  19. const idx = kmp.match(corpus);
  20. if (idx !== corpus.indexOf(pattern))
  21. throw (new Error('Please file an issue'));
  22. }
  23. // you can specify offset!
  24. {
  25. const pattern = "123";
  26. const corpus = "123abc123";
  27. const corpusOffset = 1;
  28. const idx = Kmp.KnuthMorrisPratt(pattern).match(corpus, corpusOffset);
  29. if (idx !== corpus.indexOf(pattern, corpusOffset))
  30. throw (new Error('Please file an issue'));
  31. }

Run tests

  1. npm install -D # install dev dependencies
  2. npm test # run tests

References

See also

You might be interested to Boyer–Moore–Horspool algorithm

License

See LICENSE file