Create a Calculator function in JavaScript

JavascriptWeb DevelopmentObject Oriented Programming

We have to write a function, say calculator() that takes in one of the four characters (+, - , *, / ) as the first argument and any number of Number literals after that. Our job is to perform the operation specified as the first argument over those numbers and return the result.

If the operation is multiplication or addition, we are required to perform the same operation with every element. But if the operation is subtraction or division, we have to consider the first element as neutral and subtract all other elements from it or divide it by all other elements, based on the operation.

Therefore, let’s write the code for this function −

Example

const calculator = (operation, ...numbers) => {
   const legend = '+-*/';
   const ind = legend.indexOf(operation);
   return numbers.reduce((acc, val) => {
      switch(operation){
         case '+': return acc+val;
         case '-': return acc-val;
         case '*': return acc*val;
         case '/': return acc/val;
      };
   });
};
console.log(calculator('+', 12, 45, 21, 12, 6));
console.log(calculator('-', 89, 45, 21, 12, 6));
console.log(calculator('*', 12, 45, 21, 12, 6));
console.log(calculator('/', 189000, 45, 7, 12, 4));

Output

The output in the console will be −

96
5
816480
12.5
raja
Published on 24-Aug-2020 08:57:09
Advertisements