Latest news about Bitcoin and all cryptocurrencies. Your daily crypto news habit.
Did you ever feel cumbersome when you use the built in JavaScript Functions Math.max and Math.min?
We already know that this two built functions accepts a variable argument-list. For instance when using the Math.max to get the highest value it may be written in this way
Math.max(5,2,1,3,4) // Outputs 5.
Works pretty well. How about if we’re dealing with array of values we might write our code in this way.
const list = [5,2,1,3,4];
Math.max(list[0],list[1],list[2],list[3],list[4]);
What’s wrong in this Implementation?
I guess you know what’s wrong in this. As you may notice this implementation is not flexible. What if the size of array grows? We add more values in Math.max argument. As a developer we didn’t want to do that we do hard code the values. Unless we know the size of array are we dealing with.
How do we fix this problem? Apply function to the rescue.
So we will use the Apply function to supply a variable arguments in Math.max and Math.min
For instance:
function max(array) { return Math.max.apply(Math, array);}
function min(array) { return Math.min.apply(Math, array);}
max([5,2,1,3,4]); // Outputs 5min([5,2,1,3,4]); // Outputs 1
This is equivalent to what we did before but now we’re using a built in JavaScript apply function. The value that we pass in the argument transform into comma separated value for instance: ([5,2,1,3,4] -> 5,2,1,3,4).
Now our Math.max and Math.min is now flexible it can now handle a large array of values without getting worried in it.
Hope it Helps ^_^
Follow me on twitter https://twitter.com/llaudevc
Tricks in using JavaScript Apply function was originally published in Hacker Noon on Medium, where people are continuing the conversation by highlighting and responding to this story.
Disclaimer
The views and opinions expressed in this article are solely those of the authors and do not reflect the views of Bitcoin Insider. Every investment and trading move involves risk - this is especially true for cryptocurrencies given their volatility. We strongly advise our readers to conduct their own research when making a decision.