2

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.

user5124106
  • 393
  • 2
  • 3
  • 11
  • 1
    Questions asking for a tool, lib etc. are considered off topic... have you looked at underscore.js? – reto Aug 05 '15 at 06:28
  • Yes, see [Array.prototype.find()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find). – DavidRR Mar 11 '20 at 11:10

3 Answers3

6

As you already got the mapping, javascript's Object allows you to directly lookup by key, just check if the object with the key is exist or not.

So you can just use the e.keyCode as key to find if there's a mapping to it.

var arrowKeyMap = { 37 : "left", 38: "down", 39: "right", 40: "up" };
$(document).keydown(function (e)
{
    var key = arrowKeyMap[e.keyCode];
    if (key) { // Do something if there's a map to the key.
       SG.snake.changeDirection(key );  
    }
});
fuyushimoya
  • 9,715
  • 3
  • 27
  • 34
2

You're thinking too much in terms of algorithms. Think instead in terms of data structures:

if (arrowKeyMap[e.keyCode]) { // keymap exist?
    SG.snake.changeDirection(arrowKeyMap[e.keyCode]);
}
slebetman
  • 109,858
  • 19
  • 140
  • 171
0

You can use JSLinq. It provides the same linq functions for js those are available for c#.

Akshay
  • 530
  • 7
  • 20