find the mode of a list of numbers in typescript

To find the mode of a list of numbers in TypeScript, you can use the following function:

index.ts
function mode(numbers: number[]): number | null {
  if (numbers.length === 0) {
    return null;
  }

  const countMap = new Map<number, number>();
  let maxCount = 0;
  let mode = null;

  for (const num of numbers) {
    const count = (countMap.get(num) ?? 0) + 1;
    countMap.set(num, count);

    if (count > maxCount) {
      maxCount = count;
      mode = num;
    }
  }

  return mode;
}
396 chars
22 lines

This function takes an array of numbers and returns the mode as a number, or null if the input array is empty. It uses a Map to count the occurrences of each number, and keeps track of the maximum count and corresponding mode as it iterates through the array. If there are multiple modes (i.e. multiple numbers with the same highest count), the function will return just one of them.

Here's an example usage of the function:

index.ts
const numbers = [1, 2, 2, 3, 4, 4, 4];
const result = mode(numbers);
console.log(result); // output: 4
103 chars
4 lines

In this example, the mode of the array [1, 2, 2, 3, 4, 4, 4] is 4.

gistlibby LogSnag