Skip to main content
edited tags; edited title
Link
200_success
  • 144.2k
  • 22
  • 188
  • 473

Optimize jQuery plugin according to DRY-principledetect Konami cheat code sequence

deleted 198 characters in body
Source Link
Jamal
  • 34.9k
  • 13
  • 133
  • 237

According to the DRY-principle, any ideas how to writeHow can this be written a bit shorter?

jQuery.konami = function(fn, code) {
    // ↑ ↑ ↓ ↓ ← → ← → B A
    code = code || [38, 38, 40, 40, 37, 39, 37, 39, 66, 65];

    var kkeys = '',
        i = 0;

    $(document).keydown(function(e) {
        var char = String.fromCharCode(e.which).toLowerCase();
        if (char === code[i++]) {
            kkeys += char;

            if (kkeys === code) {
                fn();
                kkeys = '';
                i = 0;
            }
        } else if (e.which === code[kkeys++]) {
            if (kkeys === code.length) {
                fn();
                kkeys = '';
                i = 0;
            }
        } else {
            kkeys = '';
            i = 0;
        }
    });
};

Update

Thanks to NickLarsen for his help. Here's the final code.

According to the DRY-principle, any ideas how to write this a bit shorter?

jQuery.konami = function(fn, code) {
    // ↑ ↑ ↓ ↓ ← → ← → B A
    code = code || [38, 38, 40, 40, 37, 39, 37, 39, 66, 65];

    var kkeys = '',
        i = 0;

    $(document).keydown(function(e) {
        var char = String.fromCharCode(e.which).toLowerCase();
        if (char === code[i++]) {
            kkeys += char;

            if (kkeys === code) {
                fn();
                kkeys = '';
                i = 0;
            }
        } else if (e.which === code[kkeys++]) {
            if (kkeys === code.length) {
                fn();
                kkeys = '';
                i = 0;
            }
        } else {
            kkeys = '';
            i = 0;
        }
    });
};

Update

Thanks to NickLarsen for his help. Here's the final code.

How can this be written a bit shorter?

jQuery.konami = function(fn, code) {
    // ↑ ↑ ↓ ↓ ← → ← → B A
    code = code || [38, 38, 40, 40, 37, 39, 37, 39, 66, 65];

    var kkeys = '',
        i = 0;

    $(document).keydown(function(e) {
        var char = String.fromCharCode(e.which).toLowerCase();
        if (char === code[i++]) {
            kkeys += char;

            if (kkeys === code) {
                fn();
                kkeys = '';
                i = 0;
            }
        } else if (e.which === code[kkeys++]) {
            if (kkeys === code.length) {
                fn();
                kkeys = '';
                i = 0;
            }
        } else {
            kkeys = '';
            i = 0;
        }
    });
};
edited tags
Link
rolfl
  • 97.5k
  • 17
  • 218
  • 418
Post Migrated Here from stackoverflow.com (revisions)
Source Link
yckart
  • 141
  • 1
  • 1
  • 6
Loading