I'm trying to get this function done but something is wrong, it should return 50 for a=5,b=10 or 2 for a=1,b=1. However any other way to write this function would be interesting
function getLargestExpressionResult(a, b) {
const sum = a b;
const prod = a * b;
const diff = a - b;
const quot = a \ b;
let res = sum;
if (prod > res) res = prod;
if (diff > res) res = diff;
if (quot > res) res = quot;
return res;
}
enter code here
CodePudding user response:
You can use Math.max()
. It can take multiple parameters and gives you max.
Also for division it is /
function getLargestExpressionResult(a, b) {
const sum = a b;
const prod = a * b;
const diff = a - b;
const quot = a / b;
return Math.max(sum,prod,diff,quot);
}
console.log(getLargestExpressionResult(5, 10))
CodePudding user response:
You don't really need to find maximum element on your own, you can simply use Math.max:
const getLargestExpressionResult = (a, b) => Math.max(a * b, a / b, a b, a - b);
console.log(getLargestExpressionResult(5, 10));
console.log(getLargestExpressionResult(1, 1));
Also should be noticed division is /
, not \
.
Or if you need to avoid Math usage:
getLargestExpressionResult = (a, b) => {
const expressionValues = [ a b, a - b, a * b, a / b ];
let max = expressionValues[0];
for (const value of expressionValues) {
if (value > max) max = value;
}
return max;
}
console.log(getLargestExpressionResult(5, 10));
console.log(getLargestExpressionResult(1, 1));