big pp in typescript

To make a function that returns the biggest number of an array of numbers in TypeScript, you can use the reduce() method:

index.ts
function findBiggest(numbers: number[]): number {
  return numbers.reduce((prev, current) => {
    return prev > current ? prev : current;
  });
}
147 chars
6 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.ts
function findBiggest<T>(arr: T[], compareFn: (a: T, b: T) => number): T {
  return arr.reduce((prev, current) => {
    return compareFn(prev, current) > 0 ? prev : current;
  });
}
181 chars
6 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.ts
const numbers = [1, 2, 3, 4, 5];
const biggestNumber = findBiggest(numbers, (a, b) => a - b);
console.log(biggestNumber); // Output: 5

const strings = ['apple', 'banana', 'cherry'];
const longestString = findBiggest(strings, (a, b) => a.length - b.length);
console.log(longestString); // Output: "banana"
306 chars
8 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