I'm a Junior-level JavaScript developer and I find that I often have situations where I need to do the equivalent of
"Find the first element satisfying a condition, then do something with the element"
and I end up writing a for
loop with a break
statement. For instance, here is a piece of production code I wrote:
// set up event listeners for changing the snake's direction
// based on arrows keys pressed
// see: http://stackoverflow.com/questions/6226859/how-can-i-track-arrow-keys-in-chrome-and-ie
var arrowKeyMap = { 37 : "left", 38: "down", 39: "right", 40: "up" };
$(document).keydown(function (e)
{
// want to make this more compact ...
for (var i in arrowKeyMap)
{
if (i == e.keyCode)
{
SG.snake.changeDirection(arrowKeyMap[i]);
break;
}
}
});
I want to know if there is a native JavaScript tool, or a way using JQuery, make that more compact, or if I need to hand-roll a reusable procedure for situations like this. I know that C# has a FirstOrDefault
and C++ a find_if
which are kinda like what I want.