Ryan
Ryan

Reputation: 618

Replacing Switch-Case with something better?

I am working on a Web chat application. The code you see above is used to process data from responses received in JSON format. Basically how it works is an Ajax long-poll request is sent to the server, which pulls the messages that need to be sent to the user. Outputs in JSON format, parsed by JS, and then Minte.Processor.process(json) is called to handle the rest.

I would like to replace the switch statement with something else. As you can see there are quite a few commands (and I'm estimating at least 50 more) so I need a more elegant solution. I was thinking of creating an object that holds an array of key-value pairs where the key is the command name and value is data, but I don't know if that is less efficient than switch.

Upvotes: 1

Views: 686

Answers (2)

aroth
aroth

Reputation: 54836

You could create a handler object that knows how to handle each command and has a method for each one. Something roughly like:

var myHandler = {
    addChatNotice: function(content) {
        Minte.UI.addChatNotice(content);
    }, 

    changeUsername: function(content) {
        Minte.Client.username = content;
    }

    //etc...
};

Minte.Processor.process = function(json) {
    for (var x in json) {
        var entry = json[x]; 

        for (var command in entry) {
            var content = entry[command];

            //invoke the handler function with the content
            myHandler[command](content);
        }
    }
};

Here's a simple example: http://jsfiddle.net/XLrN5/

Upvotes: 3

alex
alex

Reputation: 490423

You could have an Object with properties, of whom their name is the function and an anonymous function assigned to each...

var handlers = {
    'changeUsername' : function(content) {
         Minte.Client.username = content; 
    },
    ...
};

var thisCommand = handlers[command];

if (thisCommand) {
   thisCommand.call(this, content);
}

The first argument to each of the anonymous functions will be the content variable.

Upvotes: 2

Related Questions