A featherweight utility to detect a sequence of key presses or a stream, and call the supplied callback. Fast!
var keySequence = ; // CommonJS<script src="key-sequence.min.js"></script> // Browser// Regex '+'/'*' (denotes repeatable characters)// The below matches 'omg<enter>'/'omgggg<enter>'/'o mggggggg<enter>'var onKey =;// Konami codevar onKey =;// Use with ObservablessourceKeyStream;// Can pass keycode using e.which using jQuery or events.;// or pass the character itself.;/* Some more supported keysequences: */17 'c' //The classic <ctrl> and 'c''I' '.*' 'U' // I <anything in between> U
*as wildcards to denote repeating characters.
- Support for keyCodes, so you can use metakeys like
<alt>in the sequence.
- Support for meta characters like
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.
- Support for more Regex metacharacters like
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