AJMAL KAREEM
AJMAL KAREEM

Reputation: 53

In Javascript, simple calculator, not working

I tried to get numbers by prompt(), and also action name. But the result is not as expected

i am new to programming.. code:

function add(n1, n2){   return n1 + n2;}

function sub(n1, n2){   return n1 - n2;}

function mult(n1, n2){  return n1 * n2;}

function div(n1, n2){   return n1/n2;}


function calculator(n1, n2, action){

    alert(action(n1, n2));
}

calculator(prompt("first no,"), prompt("second No"), prompt("calc"));

Upvotes: 1

Views: 133

Answers (3)

Bar Yemini
Bar Yemini

Reputation: 48

I suggest you take time to learn some basics, you can't convert a string to a function call unless you use eval() like this:

function add(n1, n2){ return n1 + n2;}
function sub(n1, n2){ return n1 - n2;}
function mult(n1, n2){ return n1 * n2;}
function div(n1, n2){ return n1/n2;}

function calculator(n1, n2, action){
alert(eval(`${action}(${n1}, ${n2})`));
}

calculator(prompt("first no,"), prompt("second No"), prompt("calc"));

But this is really hacky and unsafe code, a better approach would be:

const ops = {
"add": (n1, n2) => n1 + n2,
"sub": (n1, n2) => n1 - n2,
"mult": (n1, n2) => n1 * n2,
"div": (n1, n2) => n1/n2
}

function calculator(n1, n2, action){
alert(ops[action](parseFloat(n1), parseFloat(n2)));
}

calculator(prompt("first no,"), prompt("second No"), prompt("calc"));

Also notice the parseFloat(), if you keep the parameters as strings you will get:

input: "1", "2", "add" output: "12"

Upvotes: 2

Subesh Bhandari
Subesh Bhandari

Reputation: 1112

Two things you need to do:

  1. Parse the input as float
  2. Map the function name given by the user

function add(n1, n2) { return n1 + n2; }
function sub(n1, n2) { return n1 - n2; }
function mult(n1, n2) { return n1 * n2; }
function div(n1, n2) { return n1 / n2; }

function calculator(n1, n2, action) {
  alert(action(n1, n2));
}

function findOperation(name) {
  switch (name) {
    case "sub":
      return sub;
    case "mult":
      return mult;
    case "div":
      return div;
    case "add":
    default:
      return add;
  }
}

calculator(
  parseFloat(prompt("first no,")),
  parseFloat(prompt("second No")),
  findOperation(prompt("Operation Name?"))
);

Upvotes: 5

ensleep
ensleep

Reputation: 11

the calculator function should be :

function calculator(n1, n2, action){

    alert(eval(action+'('+n1+', '+n2+')'));
}

Upvotes: 0

Related Questions