https://github.com/ashubham/key-sequence
Detect a sequence of key presses.
https://github.com/ashubham/key-sequence
Last synced: 22 days ago
JSON representation
Detect a sequence of key presses.
- Host: GitHub
- URL: https://github.com/ashubham/key-sequence
- Owner: ashubham
- License: mit
- Created: 2016-03-28T04:56:47.000Z (about 9 years ago)
- Default Branch: master
- Last Pushed: 2016-04-01T09:08:10.000Z (about 9 years ago)
- Last Synced: 2025-03-01T03:26:47.133Z (about 2 months ago)
- Language: JavaScript
- Size: 32.2 KB
- Stars: 10
- Watchers: 3
- Forks: 1
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
[](https://www.npmjs.org/package/key-sequence)
A featherweight utility to detect a sequence of key presses or a stream, and call the supplied callback. Fast!
### Usage
```javascript
var keySequence = require('key-sequence'); // CommonJS
// Browser// Regex '+'/'*' (denotes repeatable characters)
// The below matches 'omg'/'omgggg'/'o mggggggg'
var onKey = keySequence(['o', '\s*', 'm', 'g+', '\n'], (evt) => {
// Do what needs to be done when the key sequence is detected.
console('OMG it works!', evt);
});// Konami code
var onKey = keySequence([38, 38, 40, 40, 37, 39, 37, 39, 'b', 'a'], () => {
console.log('Achievement unlocked!!');
});// Use with Observables
sourceKeyStream.subscribe(
k => onKey(k));// Can pass keycode using e.which using jQuery or events.
$(document).keypress(function(e) {
onKey(e.which, e /* optional */);
});// or pass the character itself.
onKey('x');/* Some more supported keysequences: */
[17, 'c'] //The classic and 'c'
['I', '.*', 'U'] // I U
```### Features
* Supports `+` and `*` as wildcards to denote repeating characters.
* Support for keyCodes, so you can use metakeys like ``, `` in the sequence.
* Support for meta characters like `\s`, `.` etc.### Wait, but why ? I'd rather use a regex.
Using a regex is slow and cannot get less elegant, its `O(n)` in the size of your total input,
on every single keystroke.`key-sequence` generates a DFA and maintains the state. `O(1)` every single keystroke.
Can think of it as a regex which accepts streaming input.### TODO
> - Support for more Regex metacharacters like `|` etc.
### Theory

This is the DFA for the above example. `key-sequence` maintains the present state according to the key input.
Once the end state(`4` in this case) is reached the supplied `done` callback is called.If, at any point the input does not match a transition, we go back to the starting state `(0)`.