How do I select the variable associated with the highest number? If I have p1 =1 , p2=4 and p3=3, how can I make the program choose the highest one(in this case p2?)
1 Answer
You should apply a scope to the parameters, so that you reduce the number of variables you need to scan for.
let myScope = {};
myScope.p1 = 1;
myScope.p2 = 4;
myScope.p3 = 3;
console.log(getHighest(myScope)); // 4
function getHighest(scope) {
return Math.max.apply(Math, Object.values(scope));
}
Note: A better alternative would be to have a variable called p to store the values e.g.
var p = [ 1, 4, 3 ];
var max = Math.max.apply(Max, p);
NOT ADVISED: You could also access them from the window, but this is tricker...
var p1 = 1;
var p2 = 4;
var p3 = 3;
console.log(getHighest(window, /^p\d$/)); // 4
function getHighest(scope, pattern) {
return Math.max.apply(
Math,
Object.keys(scope)
.filter(k => k.match(pattern))
.map(k => scope[k])
);
}
6 Comments
Gerardo Furtado
This is not necessary.
yqlim
In case anyone reading this asks "why not just
Math.max(p1, p2, p3)", this approach does not require you to manually key in your keys everytime you add values to the scope. This can also be done using Array instead of object literal.Gerardo Furtado
@YongQuan indeed, but look at the word need: "You need to apply a scope to the parameters...". And also a comment in the question, by the same answerer: "You need to scope them". It's not necessary.
yqlim
@GerardoFurtado I agree. You don't need to do this if your context doesn't require dynamically adding values.
Mr. Polywhirl
@MarkMeyer I went ahead and updated/annotated the response. Thanks.
|
consr foo = Math.max(p1, p2, p3).