To make a function that returns the biggest number of an array of numbers in TypeScript, you can use the reduce()
method:
index.ts147 chars6 lines
Here, numbers
is an array of numbers, which is passed into the findBiggest()
function. The reduce()
method is then called on the numbers
array. The first parameter of reduce()
is a callback function that takes in two arguments, prev
and current
. The callback returns whichever is the bigger number in order to ultimately find the biggest number in the array.
To make the function more reusable, you can use generics to allow for any type of array to be passed in:
index.ts181 chars6 lines
Here, T
is a generic type parameter, which allows for any type of array to be passed in. You would call this function like this:
index.ts306 chars8 lines
As you can see, you can now pass in any type of array, as long as you provide a compareFn
callback function that determines how to compare the elements in the array.
gistlibby LogSnag