I want to write a function that performs arithmetic on ALL the arguments supplied. So for instance, if I do:
calculate('+', 3, 5, 6)
It should return 14 (which is 3+5+6)
Or if I do
calculate('*', 6,3,6,8,)
It should return 864 (which is the equivalent of multiplying all those numbers).
The function should essentially be able to handle any amount of numbers I supply to it, while also being able to handle the main arithmetic operators such as + - / *
I'm new at programming. I've tried:
function mCalc(_operator){
if(_operator=='+'){
return arguments + arguments;
}
}
console.log(mCalc('+',5,5));
this is not working so i can't even move forward.
In each function you have an arguments object see the section Rest, default, and destructured parameters as it states:
The arguments object can be used in conjunction with rest, default, and destructured parameters.
function foo(...args) { return args; }
Once you have all the arguments which are needed for your calculation just use Array.prototype.reduce()
. As the documentation which states:
The reduce() method executes a reducer function (that you provide) on each element of the array, resulting in a single output value.
I guess you can use as the following:
const mCalc = (_operator, ...args) => { if(_operator === '+') { return args.reduce((a, c) => a + c, 0); } // rest what you want to implement } const result = mCalc('+', 3, 5, 6, 2); console.log(result);
I hope that helps!
You could take an object for the operators and reduce the values by using a function which returns a function for two operands.
By calling the function the operator is taken and the values are taken to an array by using rest parameters ...
.
This approach uses arrow functions , like
calculate = (op, ...values) => values.reduce(take(op));
^^^^^^^^^ name of the function/variable
^^^^^^^^^^^^^^^ parameters
^^ arrow
^^^^^^^^^^^^^^^^^^^^^^^ return value
const operators = { '+': (a, b) => a + b, '*': (a, b) => a * b }, take = op => operators[op], calculate = (op, ...values) => values.reduce(take(op)); console.log(calculate('+', 3, 5, 6)); // 14 console.log(calculate('*', 6, 3, 6, 8));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.