Question:
Write a function max that calculates the maximum of an arbitrary number of numbers.
Example: max(1, 2) should return 2 and max(2, 3, 1) should return 3.
Answer:
function max () {
let acb = [...arguments];
acb.sort((a, b) => b - a);
return acb[0];
}
> we declare a function max
> it has no parameters
> we declare a variable 'acb'
> we initialize it with a value using the spread operator
> spread operator converts our arguments / numbers which are strings to arrays
> we then use the sort method, on our array 'acb' created by the spread operator,
> we use the sort method to arrange the numbers in our array in descending order
> like this: acb.sort((a,b) => b - a )
> if we wanted to arrange the numbers in our array in ascending order we can do the opposite
> like this: acb.sort((a,b) => a - b )
> so basically we convert the string in to array and then sort the array in descending order
> now in order to get the maximum number we simply return the first element of our array
> like this: return acb[0]
> we shall get our maximum number
No comments:
Post a Comment