Amogh Talpallikar
Amogh Talpallikar

Reputation: 12184

What is wrong in this higher order function?

mathOp =  function(type){
            return (
               "add" == type?  function(a,b){return a + b}
              :"mul" == type?  function(a,b){return a * b}
              :"sub" == type?  function(a,b){return a - b}
              :"div" == type?  function(a,b){return a / b}

            )
         }

Chrome JS debugger tool says: SyntaxError: Unexpected token )

What is wrong with this syntax ?

Upvotes: 1

Views: 145

Answers (2)

Matt Fenwick
Matt Fenwick

Reputation: 49095

As was already mentioned, a : was missing.

However, here's another way to improve this code. Put the operations in a table (implemented as an object):

var ops = {
  add: function(a, b) {return a + b;},
  mul: function(a, b) {return a * b;},
  sub: function(a, b) {return a - b;},
  div: function(a, b) {return a / b;}
};

then have mathOp perform a table lookup, taking appropriate error-handling if no op is found:

function mathOp(mytype) {
    var op = ops[mytype];
    if(!op) {
        ... error-handling ...
    }
    return op;
}

This has the advantages that the op functions are only created once instead of each time mathOp is called, it's more easily extensible, and the table can be used by other functions if need be.

Upvotes: 4

ThiefMaster
ThiefMaster

Reputation: 318518

You forgot the last : else part.

mathOp =  function(type){
            return (
               "add" == type?  function(a,b){return a + b}
              :"mul" == type?  function(a,b){return a * b}
              :"sub" == type?  function(a,b){return a - b}
              :"div" == type?  function(a,b){return a / b}
              : function() { return NaN; /* or throw an exception */ }
            )
         }

You could make it more readable by using switch():

function mathOp(type) {
    switch(type) {
        case 'add': return function(a,b) { return a + b; };
        case 'mul': return function(a,b) { return a * b; };
        case 'sub': return function(a,b) { return a - b; };
        case 'div': return function(a,b) { return a / b; };
    }
}

Upvotes: 5

Related Questions