200.Land

deduplicate.ts

The TypeScript code defines a type alias OccurrenceMap and a function getDuplicates. The function takes a readonly array, calculates the occurrence of each element, and returns an object that maps each element (that appears more than once) to its frequency. It leverages TypeScript's utility types to work with both number and string arrays.

type OccurrenceMap<T extends readonly string[] | readonly number[]> = Record<T[number], number>;

function getDuplicates(arr: readonly any[]): OccurrenceMap<typeof arr> {
  const reducer = (a: OccurrenceMap<typeof arr>, b: string) => ({
    ...a,
    [`${b}`]: a[`${b}`] + 1 || 1,
  });
  const res: OccurrenceMap<typeof arr> = arr.reduce(reducer);
  return Object.fromEntries(Object.entries(res).filter((e) => e[1] > 1));
}