nntrn
2/20/2019 - 7:55 PM

[Using Dispatch Tables to Avoid Conditionals in JavaScript] #adripofjavascript

[Using Dispatch Tables to Avoid Conditionals in JavaScript] #adripofjavascript

In this refactored version we are using a dispatch table to hold all the possible commands a user can give, and the functions the program should call. That changes the processUserInput function into a single line, and eliminates all conditionals.

If you are unfamiliar with bracket notation, it is just an alternate way of accessing a function's properties, with the advantage that you can use variables for the property's name. For example, if command is "north", then commandTable[command] is equivalent to commandTable.north.

The fundamental change we made is transforming the conditionals into a data structure. And data is much easier to manipulate than conditionals. In the future, if we want to add a new command, all we have to do is add it to commandTable. No messing around with case or break statements required.

source: http://adripofjavascript.com/blog/drips/using-dispatch-tables-to-avoid-conditionals-in-javascript.html

var commandTable = {
    north:    function() { movePlayer("north"); },
    east:     function() { movePlayer("east");  },
    south:    function() { movePlayer("south"); },
    west:     function() { movePlayer("west");  },
    look:     describeLocation,
    backpack: showBackpack
}

function processUserInput(command) {
    commandTable[command]();
}
function processUserInput(command) {
    switch (command) {
        case "north":
            movePlayer("north");
            break;
        case "east":
            movePlayer("east");
            break;
        case "south":
            movePlayer("south");
            break;
        case "west":
            movePlayer("west");
            break;
        case "look":
            describeLocation();
            break;
        case "backpack":
            showBackpack();
            break;
    }
}