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;
}
});
};
2 Answers 2
This is almost like code golf; this could probably be shortened. You just need to keep track of i
and when it's past the end of the array, you know all the keys were hit in the correct order.
jQuery.konami = function() {
function KonamiCode(kFn, kCode) {
var i = 0;
$(document).keydown(function(e) {
var char = typeof kCode === 'string' ? String.fromCharCode(e.which).toLowerCase() : e.which;
i = char === kCode[i] ? i + 1 : 0;
if (i === kCode.length) {
kFn();
i = 0;
}
});
}
return function(fn, code) {
// ↑ ↑ ↓ ↓ ← → ← → B A
kCode = code || [38, 38, 40, 40, 37, 39, 37, 39, 66, 65];
new KonamiCode(fn, kCode);
};
}();
-
\$\begingroup\$ nice approach, but works not as expected... \$\endgroup\$yckart– yckart2012年11月30日 15:19:19 +00:00Commented Nov 30, 2012 at 15:19
-
\$\begingroup\$ @yckart what's wrong with it? \$\endgroup\$Nick Larsen– Nick Larsen2012年11月30日 15:20:38 +00:00Commented Nov 30, 2012 at 15:20
-
\$\begingroup\$ yeah it just simply isn't working, :p jsfiddle.net/dxPdw/5 I haven't investigated as to why though \$\endgroup\$user400654– user4006542012年11月30日 15:22:36 +00:00Commented Nov 30, 2012 at 15:22
-
\$\begingroup\$ @NickLarsen it breaks on multiple instantiations and even fails with strings (words)... jsfiddle.net/ARTsinn/dxPdw/6 \$\endgroup\$yckart– yckart2012年11月30日 15:22:53 +00:00Commented Nov 30, 2012 at 15:22
-
\$\begingroup\$ Silly logic error,
i = char === code[i] ? 0 : i + 1;
needed to bei = char === code[i] ? i + 1 : 0;
. \$\endgroup\$Nick Larsen– Nick Larsen2012年11月30日 15:25:31 +00:00Commented Nov 30, 2012 at 15:25
Here's a slightly shortened version:
jQuery.konami = function(fn, code) {
// ↑ ↑ ↓ ↓ ← → ← → B A
code = code || [38, 38, 40, 40, 37, 39, 37, 39, 66, 65];
var i = 0;
$(document).keydown(function(e) {
var char = $.type(code[i]) === "string" ? String.fromCharCode(e.which).toLowerCase() : e.which;
if (char === code[i]) {
i++;
if (i == code.length) {
fn();
i = 0;
}
} else {
i = 0;
}
});
};
the kkeys var wasn't needed, and you could move the if else into the retrieval of char
, allowing you to reuse what was inside the if originally.
-
\$\begingroup\$ Nice! However, got it already stackoverflow.com/questions/13647824/… ;-) \$\endgroup\$yckart– yckart2012年11月30日 15:42:13 +00:00Commented Nov 30, 2012 at 15:42
Explore related questions
See similar questions with these tags.