修复: `arrayUnique` 为 O(n²),并将包含 `NaN` 的数组报告为非唯一

作者: itamar-gerasy创建于 2026年8月25日更新于 2026年9月12日
标签type: fixstatus: needs triage

arrayUnique 使用 Array.prototype.indexOfArray.prototype.filter 中决定唯一性。对于具有不同值的数组,其最坏情况下的时间复杂度为 O(n²)。

此外,它还将包含 NaN 的数组报告为非唯一,包括只出现一次 NaN 的数组。这两种行为都源自同一个实现,位于 src/decorator/array/ArrayUnique.ts 中:

typescript
export function arrayUnique(array: unknown[], identifier?: ArrayUniqueIdentifier): boolean {
  if (!Array.isArray(array)) return false;

  if (identifier) {
    array = array.map(o => (o != null ? identifier(o) : o));
  }

  const uniqueItems = array.filter((a, b, c) => c.indexOf(a) === b);
  return array.length === uniqueItems.length;
}

问题 1 — 二次最坏情况成本

内容来源: typestack/class-validator