[TypeScript] Find the repeated item in an array using TypeScript

Say you have an array that has at least one item repeated. How would you find the repeated item. This is a question commonly presented to beginner developers. Here we discuss the elegant solution to this problem.

 

export function repeatedItem<T>(array: T[]): T {
  const set = new Set<T>();
  for (const item of array) {
    if (set.has(item)) return item;
    else set.add(item);
  }
  throw new Error('No item repetition');
}

 

posted @ 2017-04-28 02:45  Zhentiw  阅读(221)  评论(0编辑  收藏  举报