
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Create a Calculator Function in JavaScript
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
Advertisements