Best Way to Format a Simple When Function in JS

Viewed 53

I found this code in Ruby (from here):

DX = { E => 1, W => -1, N =>  0, S => 0 }

and I was thinking about how to best format it in JS, given that it's lacking a "when" function.

For reference, N, S, E, and W are "directions", and have aliases like so: const N = 1, S = 2, E = 4, W = 8;

I originally wanted to make a quick arrow function, but then went with this:

function DX(dir) {
    if(dir==E) return 1;
    if(dir==W) return -1;
    if(dir==N) return 0;
    if(dir==S) return 0;
}

That looked a little long to me, so I tried to shorten it:

function DX(dir) {
    if(dir==E) return 1;
    if(dir==W) return -1;
    return 0;
}

And then again:

function DX(dir) {
    return dir==E ? 1 : dir==W ? -1 : 0;
}

But now we reach the problem that this code isn't very readable. So I decided to document it:

// returns the distance in x traveled by that direction
// E => 1, W => -1, N =>  0, S => 0
function DX(dir) {
    return dir==E ? 1 : dir==W ? -1 : 0;
}

And then lastly, I converted it to variable syntax and an arrow function:

let DX = (dir) => dir==E ? 1 : dir==W ? -1 : 0;

Now obviously, all of this code works, but my question is as a manner of style, which is considered "best", either in industry, in your opinion, or where you specifically work? I assume readability is above all else, so which code is most readable in your opinion? I prefer the section with the documentation, personally.

3 Answers

By using an object as suggested above by several users, we can make this code much simpler. However, we ran into the problem of objects using the literal strings "N", "S", "E", and "W" instead of the variables' numeric values 1, 2, 4, and 8.

I found the answer to this problem on SO which is just adding square brackets (in ES6):

const N = 1, S = 2, E = 4, W = 8;
const DX = { [E]: 1, [W]: -1, [N]: 0, [S]: 0 };

It can be used with: DX[dir]

Just take the same with an object.

const DX = { E: 1, W: -1, N: 0, S: 0 };

// use
value = DX[dir];

For using with numerical values as direction, you need to map the keys to the directions.

//           N     S     E     W
const DX = { 1: 0, 2: 0, 4: 1, 8: -1 };

// use
value = DX[dir];

I would recommend you create an object which maps the directions to the aliases and use it to return the right alias from the function.

const DX = dir => {
    mapping = { E: 1, W: -1, N: 0, S: 0 };
    return mapping[dir];
}
Related