pbojinov
11/3/2014 - 7:25 PM

using dispatch tables - aka avoid using switch

using dispatch tables - aka avoid using switch

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

// avoid this, switch blah 
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;
    }
}

// much easier to manipulate conditionals
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]();
}