Question

So for example, I would like to evaluate 2(3) [which equates to 6].

var string = "2(3)";
var ans = eval(string);

I typed in the above code in Chrome Console and they gave me the following error message: TypeError: number is not a function.

So how do I get "2(3)" to return 6? Thx.

Was it helpful?

Solution

You can use a regular expression to insert a * between any digit followed by an open bracket to convert your string from 2(3) to 2*(3) before passing it through eval():

var string = "2(3)",

    // Convert string to array (["2", "(", "3", ")"])
    array = string.split(''),

    ans;

// Insert * between digit and open bracket  (["2", "*", "(", "3", ")"])
array.splice(string.search(/\d\(/) + 1, 0, "*");

// Convert array back to string ("2*(3)")
string = array.join("");

// Run eval (6)
ans = eval(string);

console.log(ans);

JSFiddle demo.

OTHER TIPS

JavaScript doesn't do that. What you you can do, however, is create a function that returns a function. The second function is called a closure. It's handy because when it's returned it maintains a copy of the local environment it was in when it was created. So you pass in a multiplier parameter to the first function which returns a function. This function, the closure, evaluates the parameter you pass into it when it's called by that multiplier.

Far better people have explained what a closure is than me.

function times(multiplier) {
  return function (num) {
    return num * multiplier;
  }
}

var bySix = times(2);
var result = bySix(3); // 6
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top