KeyPressTracker

by bryan_weaver

JavaScript

function KeyPressTracker(sequenceLength) { 
    var _keys = [sequenceLength];
    var _counter = 0;
    //retrieve the last key that was pressed.
    this.GetLastKey = function() {
        if (_keys[0] === null) {
            return null;
        } else {
            return _keys[_counter - 1];
        }
    };
    //get the current seqence of key codes stored.
    this.GetSequence = function() {
        return _keys;
    };
    //store a key code and increment array index counter.
    this.Store = function(keyCode) {
        _keys[_counter] = keyCode;
        _counter++;
    };
    //reset the sequence of key codes and the array index counter.
    this.Reset = function() {
        _keys = [sequenceLength];
        _counter = 0;
    };
}

//key sequence: up, up, down, down, left, right, left, right, a, b, enter
var targetSequence = [38, 38, 40, 40, 37, 39, 37, 39, 65, 66, 13];
var kpt = new KeyPressTracker(targetSequence.length);

$(document).keyup(function(e) {
    //if key pressed is not in the array ignore the value
    //and reset the current sequence of keys pressed.
    if ($.inArray(e.which, targetSequence) !== -1) {
        kpt.Store(e.which);
    } else {
        kpt.Reset();
    }
    //get the current sequence
    var currentSequence = kpt.GetSequence();
    //if current sequence is not empty and has a length equal to the target sequence.
    //compare the two arrays and determine if they are equal
    //else reset the array.
    if (currentSequence[targetSequence.length - 1] !== undefined) {
        if (currentSequence.length == targetSequence.length) {
            if (currentSequence.join('') == targetSequence.join('')) {
                //Correct sequence of keys was met.  Do something.
                alert('Match!');
            }
        } else {
            kpt.Reset();          
        }
    }
})