jsartisan / frontend-challenges

FrontendChallenges is a collection of frontend interview questions and answers. It is designed to help you prepare for frontend interviews. It's free and open source.
https://frontend-challenges.com
27 stars 4 forks source link

145 - minBy - typescript #147

Open jsartisan opened 1 month ago

jsartisan commented 1 month ago

index.ts

export function minBy<T>(array: T[], iteratee: (item: T) => number): T | undefined {
  if (array.length == 0) return;

  return array.reduce((previous, current) => {
    const previousValue = iteratee(previous);
    const currentValue = iteratee(current);

    if (previousValue > currentValue) {
      return current;
    }

    return previous;
  });
}