Search code examples
javascriptreadabilitycode-readability

Best Way to Format a Simple When Function in JS


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.


Solution

  • 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];