审查 AI 写的 BigInt 区间集合:精确端点、原子切分与有界补集

10-19 5阅读

让 AI 写一个区间集合,最容易得到的是十几行排序与合并代码:演示数据看起来正确,边界却没有真正定义。字节位置、日志序号、逻辑时钟这些整数坐标一旦超过安全整数范围,端点可能先被 Number 压成同一个值;删除操作可能把右端点多删一个单位;返回内部数组还会让调用者绕过所有校验,直接破坏排序。

本文把审查对象收敛成一个同步、内存内、拥有自身数据的 JavaScript 组件。坐标只接受 bigint 原始值,集合表示若干个整数半开区间 [lo, hi),提供批量 add、批量 remove、intersection 和 complementWithin。它不负责数据库持久化,不保存区间来源、标签或覆盖次数。合并意味着忘掉原始分段,因此不能拿它直接表达预约归属或重叠权重。

审查目标也不是让模型解释它自己的代码,而是先写出独立契约,再让实现接受反例与参考模型的检查。尤其要把两种概念分开:半开区间在端点处相接时交集为空,但在集合的规范表示中,它们仍应合并,因为并集没有空洞。这个差异会同时影响添加、求交和补集,却不能共用一个含糊的重叠判断。

审查 AI 写的 BigInt 区间集合:精确端点、原子切分与有界补集
独立生成的概念插画:用分段、连接和留白提示集合操作。图中装饰圆环不是比例尺或可执行端点定义,具体语义以正文契约和断言为准。

先把 AI 必须遵守的契约写清楚

  • 端点是任意精度的有符号整数,拒绝 Number、字符串与包装对象;负坐标合法,没有无限端点。

  • [a, a) 是合法空区间:构造时丢弃,添加和删除时无效果;[b, a) 在 b 大于 a 时抛出 RangeError,不自动调换端点。

  • 内部每段都非空、按左端点递增,相邻两段必须满足前段右端点严格小于后段左端点。相交与首尾相接都要合并。

  • add 和 remove 修改接收者并返回接收者;intersection 和 complementWithin 返回独立的新集合,不改变输入集合。

  • 同一次批量变更中的所有参数先校验,任一个非法就保留旧状态。输入数组和输出快照都不共享内部的二元数组。

本文限定输入是普通数据数组,运行在未篡改内建方法的环境。不承诺抵御带副作用的 getter、Proxy、重入回调或恶意修改原型;这里的原子性是普通同步调用中先计算后提交,不是跨线程事务,也不是内存耗尽后的恢复保证。给 AI 这样的边界,比要求它写一个完全安全的通用区间库更可检验。

下面恰好九个程序都可单独保存为所标注的 .mjs 文件,以 node --unhandled-rejections=strict 文件名.mjs 运行,无第三方依赖,无隐含的前置代码。实测环境为 Node.js v24.19.0。第三段起重复完整组件是为了独立复制运行;实际项目应保留一份实现。严格断言使用 Node.js 官方 strict assertion mode。这些例子本身同步,拒绝处理开关只是统一测试环境,不能替代区间正确性断言。

一、精确端点:先阻止精度在入口丢失

规范把 BigInt 定义为整数类型,端点之间的比较和加减无需先经过浮点数。重要的是数据来源:把一个已经舍入的 Number 再交给 BigInt,不会复原它原来想表达的整数。下面让两个相差一的巨大端点转成 Number,故意观察它们塌缩,再用断言证明这个错误不能靠事后转换修补。对外接口宁可拒绝字符串,格式解析应放在明确的适配层。

另一个高频 AI 错误是直接把 a - b 作为 BigInt 排序比较器。数组排序对比较结果执行数值转换,因此返回 bigint 会抛错。我们只使用大小比较,返回 Number 类型的负一、零、正一,端点本身仍保持 bigint。这里不是把大整数差值转换成 Number。依据见 ECMAScript 的 BigInt 类型和 CompareArrayElements;业务的拒绝策略则是本文自己的接口约定。

独立文件:01_exact_endpoints.mjs

import assert from "node:assert/strict";

function endpoint(x) {
  if (typeof x !== "bigint") throw new TypeError("expected bigint");
  return x;
}
const lo = 9007199254740992n, hi = lo + 1n;
assert.equal(hi - lo, 1n);
assert.equal(Number(lo), Number(hi));
assert.equal(BigInt(Number(hi)), lo);
assert.throws(() => endpoint(9007199254740993), TypeError);
assert.throws(() => endpoint("9007199254740993"), TypeError);
assert.throws(() => endpoint(Object(hi)), TypeError);
const cmp = (a, b) => a < b ? -1 : a > b ? 1 : 0;
assert.deepEqual([hi, -1n, lo].sort(cmp), [-1n, lo, hi]);
assert.throws(() => [2n, 1n].sort((a, b) => a - b), TypeError);
console.log(`width=${hi - lo}; collapsed=${Number(lo) === Number(hi)}`);
console.log("01 PASS: exact endpoints and numeric comparator");

精确输出:

width=1; collapsed=true
01 PASS: exact endpoints and numeric comparator

二、规范化:相接要合并,空洞不能跨越

normalize 先把每个二元数组完整校验并复制,再排序和扫描。这样既不会原地重排调用者的数组,也不会在扩展最后一段右端点时改到调用者的数据。判断新段是否独立时使用 last[1] 小于 lo:相等时进入合并分支。假如 AI 用小于等于,就会留下两个可以连接的片段,破坏规范表示的唯一性。

但 [0, 1) 与 [2, 3) 之间的整数 1 并未覆盖,因此必须保留两段。不要因为坐标是整数就给端点加一来判断相邻,那是闭区间算法的习惯。空区间在完成类型与顺序校验后丢弃,而不是让空数组、缺失元素或字符串端点冒充空集合。第二段还检查重复、嵌套、乱序、负数、幂等和输入所有权,审查时应逐项对应契约,而不只看最终合并成几段。

独立文件:02_normalize.mjs

import assert from "node:assert/strict";

function pair(value) {
  if (!Array.isArray(value) || value.length !== 2) {
    throw new TypeError("expected [bigint, bigint]");
  }
  const lo = value[0], hi = value[1];
  if (typeof lo !== "bigint" || typeof hi !== "bigint") {
    throw new TypeError("endpoints must be bigint");
  }
  if (lo > hi) throw new RangeError("reversed interval");
  return [lo, hi];
}
const cmp = (a, b) => a < b ? -1 : a > b ? 1 : 0;
function normalize(rows) {
  if (!Array.isArray(rows)) throw new TypeError("expected array");
  const copied = [];
  for (const row of rows) copied.push(pair(row));
  copied.sort((a, b) => cmp(a[0], b[0]) || cmp(a[1], b[1]));
  const out = [];
  for (const [lo, hi] of copied) {
    if (lo === hi) continue;
    const last = out.at(-1);
    if (!last || last[1] < lo) out.push([lo, hi]);
    else if (hi > last[1]) last[1] = hi;
  }
  return out;
}

const input = [[8n, 12n], [4n, 8n], [1n, 3n], [2n, 5n],
  [1n, 3n], [20n, 20n], [-4n, -2n]];
const before = input.map(row => [...row]);
const result = normalize(input);
assert.deepEqual(result, [[-4n, -2n], [1n, 12n]]);
assert.deepEqual(input, before);
assert.deepEqual(normalize(result), result);
assert.deepEqual(normalize([[0n, 1n], [2n, 3n]]), [[0n, 1n], [2n, 3n]]);
assert.deepEqual(normalize([[7n, 7n]]), []);
assert.throws(() => normalize([[0n, 1n], [4n, 2n]]), RangeError);
assert.throws(() => normalize(new Array(1)), TypeError);
result[0][0] = -99n;
assert.deepEqual(input, before);
console.log("02 PASS: sorted, nonempty, disjoint, nonadjacent, owned");

精确输出:

02 PASS: sorted, nonempty, disjoint, nonadjacent, owned

三、添加:用桥接反例检查规范表示

完整组件把状态收进私有字段。批量 add 先把旧段和新段交给 normalize,得到完整的新数组后才替换字段。两段桥接数据可把三个旧片段连成一段,这能抓住只和左邻或右邻合并一次的实现。重复添加、添加已覆盖子段与添加空区间都应保持集合含义不变。

has 的契约是左闭右开,不能把等于右端点的坐标算进去。它只接受 bigint,避免查询接口与写入接口使用不同的隐式转换规则。当前实现线性扫描,目的是先形成容易核验的正确版本;以后可以把查询换成二分查找,但不能顺便改变边界与类型规则。我们也用逆序构造和逆序添加证明同样的输入集合得到同样的规范表示,添加顺序不会变成隐藏的业务信息。

独立文件:03_add.mjs

import assert from "node:assert/strict";

function pair(value) {
  if (!Array.isArray(value) || value.length !== 2) {
    throw new TypeError("expected [bigint, bigint]");
  }
  const lo = value[0], hi = value[1];
  if (typeof lo !== "bigint" || typeof hi !== "bigint") {
    throw new TypeError("endpoints must be bigint");
  }
  if (lo > hi) throw new RangeError("reversed interval");
  return [lo, hi];
}
const cmp = (a, b) => a < b ? -1 : a > b ? 1 : 0;
function normalize(rows) {
  if (!Array.isArray(rows)) throw new TypeError("expected array");
  const copied = [];
  for (const row of rows) copied.push(pair(row));
  copied.sort((a, b) => cmp(a[0], b[0]) || cmp(a[1], b[1]));
  const out = [];
  for (const [lo, hi] of copied) {
    if (lo === hi) continue;
    const last = out.at(-1);
    if (!last || last[1] < lo) out.push([lo, hi]);
    else if (hi > last[1]) last[1] = hi;
  }
  return out;
}
function subtractOne(rows, [lo, hi]) {
  if (lo === hi) return rows;
  const out = [];
  for (const [a, b] of rows) {
    if (b <= lo || hi <= a) out.push([a, b]);
    else {
      if (a < lo) out.push([a, lo]);
      if (hi < b) out.push([hi, b]);
    }
  }
  return out;
}
class IntervalSet {
  #rows;
  constructor(rows = []) { this.#rows = normalize(rows); }
  static #fromCanonical(rows) {
    const result = new IntervalSet();
    result.#rows = rows;
    return result;
  }
  snapshot() { return this.#rows.map(([a, b]) => [a, b]); }
  has(x) {
    if (typeof x !== "bigint") throw new TypeError("expected bigint");
    return this.#rows.some(([a, b]) => a <= x && x < b);
  }
  add(...rows) {
    const next = normalize([...this.#rows, ...rows]);
    this.#rows = next;
    return this;
  }
  remove(...rows) {
    const cuts = normalize(rows);
    let next = this.snapshot();
    for (const cut of cuts) next = subtractOne(next, cut);
    this.#rows = next;
    return this;
  }
  intersection(other) {
    if (!(other instanceof IntervalSet)) throw new TypeError("expected IntervalSet");
    const a = this.#rows, b = other.#rows, out = [];
    let i = 0, j = 0;
    while (i < a.length && j < b.length) {
      const lo = a[i][0] > b[j][0] ? a[i][0] : b[j][0];
      const hi = a[i][1] < b[j][1] ? a[i][1] : b[j][1];
      if (lo < hi) out.push([lo, hi]);
      if (a[i][1] < b[j][1]) i++;
      else if (a[i][1] > b[j][1]) j++;
      else { i++; j++; }
    }
    return IntervalSet.#fromCanonical(out);
  }
  complementWithin(bounds) {
    const [lo, hi] = pair(bounds), out = [];
    let cursor = lo;
    for (const [a, b] of this.#rows) {
      if (b <= cursor) continue;
      if (a >= hi) break;
      if (cursor < a) out.push([cursor, a < hi ? a : hi]);
      if (b > cursor) cursor = b;
      if (cursor >= hi) break;
    }
    if (cursor < hi) out.push([cursor, hi]);
    return IntervalSet.#fromCanonical(out);
  }
}
const show = set => set.snapshot()
  .map(([a, b]) => `[${a},${b})`).join(" ") || "∅";

const set = new IntervalSet([[1n, 3n], [7n, 9n], [12n, 14n]]);
assert.equal(set.add([3n, 7n], [9n, 12n]), set);
assert.deepEqual(set.snapshot(), [[1n, 14n]]);
set.add([2n, 4n], [1n, 14n], [99n, 99n]);
assert.deepEqual(set.snapshot(), [[1n, 14n]]);
set.add([-4n, -2n]);
assert.equal(set.has(1n), true);
assert.equal(set.has(14n), false);
assert.equal(set.has(-3n), true);
assert.equal(set.has(0n), false);
const reversed = new IntervalSet([[12n, 14n], [7n, 9n], [1n, 3n]])
  .add([9n, 12n], [3n, 7n], [-4n, -2n]);
assert.deepEqual(set.snapshot(), reversed.snapshot());
console.log(show(set));
console.log("03 PASS: add bridges and half-open membership");

精确输出:

[-4,-2) [1,14)
03 PASS: add bridges and half-open membership

四、删除:保存两侧碎片,触边不算相交

删除不是把命中的整段过滤掉。一段 [0, 20) 减去 [5, 15),必须留下 [0, 5) 和 [15, 20)。左碎片的右端点就是 lo,右碎片的左端点就是 hi,完全不需要减一或加一。这个形式直接来自半开区间的成员条件,避免了闭区间写法迁移过来造成的错位。

subtractOne 的无交集条件采用 b 小于等于 lo 或 hi 小于等于 a,因此删除范围只碰到端点时不会改变原段。每次切割都沿原顺序输出,且只缩小覆盖范围,不会制造需要新合并的相邻片段。remove 先规范化整批切割范围,之后才在局部副本上计算;即使前一个参数有效、后一个参数倒置,也不会出现删到一半才报错。清空后的集合再次删除仍为空,空删除区间则保持不变。

独立文件:04_remove.mjs

import assert from "node:assert/strict";

function pair(value) {
  if (!Array.isArray(value) || value.length !== 2) {
    throw new TypeError("expected [bigint, bigint]");
  }
  const lo = value[0], hi = value[1];
  if (typeof lo !== "bigint" || typeof hi !== "bigint") {
    throw new TypeError("endpoints must be bigint");
  }
  if (lo > hi) throw new RangeError("reversed interval");
  return [lo, hi];
}
const cmp = (a, b) => a < b ? -1 : a > b ? 1 : 0;
function normalize(rows) {
  if (!Array.isArray(rows)) throw new TypeError("expected array");
  const copied = [];
  for (const row of rows) copied.push(pair(row));
  copied.sort((a, b) => cmp(a[0], b[0]) || cmp(a[1], b[1]));
  const out = [];
  for (const [lo, hi] of copied) {
    if (lo === hi) continue;
    const last = out.at(-1);
    if (!last || last[1] < lo) out.push([lo, hi]);
    else if (hi > last[1]) last[1] = hi;
  }
  return out;
}
function subtractOne(rows, [lo, hi]) {
  if (lo === hi) return rows;
  const out = [];
  for (const [a, b] of rows) {
    if (b <= lo || hi <= a) out.push([a, b]);
    else {
      if (a < lo) out.push([a, lo]);
      if (hi < b) out.push([hi, b]);
    }
  }
  return out;
}
class IntervalSet {
  #rows;
  constructor(rows = []) { this.#rows = normalize(rows); }
  static #fromCanonical(rows) {
    const result = new IntervalSet();
    result.#rows = rows;
    return result;
  }
  snapshot() { return this.#rows.map(([a, b]) => [a, b]); }
  has(x) {
    if (typeof x !== "bigint") throw new TypeError("expected bigint");
    return this.#rows.some(([a, b]) => a <= x && x < b);
  }
  add(...rows) {
    const next = normalize([...this.#rows, ...rows]);
    this.#rows = next;
    return this;
  }
  remove(...rows) {
    const cuts = normalize(rows);
    let next = this.snapshot();
    for (const cut of cuts) next = subtractOne(next, cut);
    this.#rows = next;
    return this;
  }
  intersection(other) {
    if (!(other instanceof IntervalSet)) throw new TypeError("expected IntervalSet");
    const a = this.#rows, b = other.#rows, out = [];
    let i = 0, j = 0;
    while (i < a.length && j < b.length) {
      const lo = a[i][0] > b[j][0] ? a[i][0] : b[j][0];
      const hi = a[i][1] < b[j][1] ? a[i][1] : b[j][1];
      if (lo < hi) out.push([lo, hi]);
      if (a[i][1] < b[j][1]) i++;
      else if (a[i][1] > b[j][1]) j++;
      else { i++; j++; }
    }
    return IntervalSet.#fromCanonical(out);
  }
  complementWithin(bounds) {
    const [lo, hi] = pair(bounds), out = [];
    let cursor = lo;
    for (const [a, b] of this.#rows) {
      if (b <= cursor) continue;
      if (a >= hi) break;
      if (cursor < a) out.push([cursor, a < hi ? a : hi]);
      if (b > cursor) cursor = b;
      if (cursor >= hi) break;
    }
    if (cursor < hi) out.push([cursor, hi]);
    return IntervalSet.#fromCanonical(out);
  }
}
const show = set => set.snapshot()
  .map(([a, b]) => `[${a},${b})`).join(" ") || "∅";

const set = new IntervalSet([[0n, 20n], [30n, 40n]]);
assert.equal(set.remove([5n, 15n]), set);
assert.deepEqual(set.snapshot(), [[0n, 5n], [15n, 20n], [30n, 40n]]);
set.remove([20n, 30n], [2n, 2n]);
assert.deepEqual(set.snapshot(), [[0n, 5n], [15n, 20n], [30n, 40n]]);
set.remove([-9n, 2n], [18n, 35n]);
assert.deepEqual(set.snapshot(), [[2n, 5n], [15n, 18n], [35n, 40n]]);
assert.equal(set.has(5n), false);
assert.equal(set.has(15n), true);
console.log(show(set));
set.remove([-100n, 100n]);
assert.deepEqual(set.snapshot(), []);
set.remove([0n, 10n]);
assert.deepEqual(set.snapshot(), []);
console.log("04 PASS: split, clip, touching, empty and full removal");

精确输出:

[2,5) [15,18) [35,40)
04 PASS: split, clip, touching, empty and full removal

五、交集:两个游标只推进已经结束的一侧

两个规范集合求交时,候选交集的左端点取较大者,右端点取较小者;只有 lo 严格小于 hi 才输出。端点相接产生的是空集,不能因为添加阶段会合并相接片段,就在这里也把相等视为非空。谁的当前右端点更早结束,谁的游标先前进;同时结束时两个都前进。

内部私有工厂直接接收算法生成的规范数组,避免结果再排序。这个入口不能开放给外部调用者,否则一份未验证数组就能绕过所有不变量。求交结果的二元数组都新建,因此继续删除结果不会改变任一输入。对称性和自交等于自身是很有用的性质,但两个同样错误的实现也可能互相一致;本段仍保留手工计算的明确结果,最后再用独立参考模型覆盖更多组合。

独立文件:05_intersection.mjs

import assert from "node:assert/strict";

function pair(value) {
  if (!Array.isArray(value) || value.length !== 2) {
    throw new TypeError("expected [bigint, bigint]");
  }
  const lo = value[0], hi = value[1];
  if (typeof lo !== "bigint" || typeof hi !== "bigint") {
    throw new TypeError("endpoints must be bigint");
  }
  if (lo > hi) throw new RangeError("reversed interval");
  return [lo, hi];
}
const cmp = (a, b) => a < b ? -1 : a > b ? 1 : 0;
function normalize(rows) {
  if (!Array.isArray(rows)) throw new TypeError("expected array");
  const copied = [];
  for (const row of rows) copied.push(pair(row));
  copied.sort((a, b) => cmp(a[0], b[0]) || cmp(a[1], b[1]));
  const out = [];
  for (const [lo, hi] of copied) {
    if (lo === hi) continue;
    const last = out.at(-1);
    if (!last || last[1] < lo) out.push([lo, hi]);
    else if (hi > last[1]) last[1] = hi;
  }
  return out;
}
function subtractOne(rows, [lo, hi]) {
  if (lo === hi) return rows;
  const out = [];
  for (const [a, b] of rows) {
    if (b <= lo || hi <= a) out.push([a, b]);
    else {
      if (a < lo) out.push([a, lo]);
      if (hi < b) out.push([hi, b]);
    }
  }
  return out;
}
class IntervalSet {
  #rows;
  constructor(rows = []) { this.#rows = normalize(rows); }
  static #fromCanonical(rows) {
    const result = new IntervalSet();
    result.#rows = rows;
    return result;
  }
  snapshot() { return this.#rows.map(([a, b]) => [a, b]); }
  has(x) {
    if (typeof x !== "bigint") throw new TypeError("expected bigint");
    return this.#rows.some(([a, b]) => a <= x && x < b);
  }
  add(...rows) {
    const next = normalize([...this.#rows, ...rows]);
    this.#rows = next;
    return this;
  }
  remove(...rows) {
    const cuts = normalize(rows);
    let next = this.snapshot();
    for (const cut of cuts) next = subtractOne(next, cut);
    this.#rows = next;
    return this;
  }
  intersection(other) {
    if (!(other instanceof IntervalSet)) throw new TypeError("expected IntervalSet");
    const a = this.#rows, b = other.#rows, out = [];
    let i = 0, j = 0;
    while (i < a.length && j < b.length) {
      const lo = a[i][0] > b[j][0] ? a[i][0] : b[j][0];
      const hi = a[i][1] < b[j][1] ? a[i][1] : b[j][1];
      if (lo < hi) out.push([lo, hi]);
      if (a[i][1] < b[j][1]) i++;
      else if (a[i][1] > b[j][1]) j++;
      else { i++; j++; }
    }
    return IntervalSet.#fromCanonical(out);
  }
  complementWithin(bounds) {
    const [lo, hi] = pair(bounds), out = [];
    let cursor = lo;
    for (const [a, b] of this.#rows) {
      if (b <= cursor) continue;
      if (a >= hi) break;
      if (cursor < a) out.push([cursor, a < hi ? a : hi]);
      if (b > cursor) cursor = b;
      if (cursor >= hi) break;
    }
    if (cursor < hi) out.push([cursor, hi]);
    return IntervalSet.#fromCanonical(out);
  }
}
const show = set => set.snapshot()
  .map(([a, b]) => `[${a},${b})`).join(" ") || "∅";

const a = new IntervalSet([[0n, 5n], [8n, 12n], [20n, 30n]]);
const b = new IntervalSet([[3n, 10n], [12n, 20n], [25n, 40n]]);
const left = a.snapshot(), right = b.snapshot();
const result = a.intersection(b);
assert.deepEqual(result.snapshot(), [[3n, 5n], [8n, 10n], [25n, 30n]]);
assert.deepEqual(result.snapshot(), b.intersection(a).snapshot());
assert.deepEqual(a.intersection(a).snapshot(), left);
assert.deepEqual(a.intersection(new IntervalSet()).snapshot(), []);
assert.deepEqual(a.snapshot(), left);
assert.deepEqual(b.snapshot(), right);
assert.deepEqual(new IntervalSet([[0n, 2n]])
  .intersection(new IntervalSet([[2n, 5n]])).snapshot(), []);
console.log(show(result));
result.remove([0n, 100n]);
assert.deepEqual(a.snapshot(), left);
assert.deepEqual(b.snapshot(), right);
console.log("05 PASS: intersection is exact, symmetric and independently owned");

精确输出:

[3,5) [8,10) [25,30)
05 PASS: intersection is exact, symmetric and independently owned

六、有界补集:先声明宇宙,再找剩余空隙

整数轴没有天然的有限全集,所以 API 必须显式接收 bounds。complementWithin([lo, hi)) 表示窗口内未被当前集合覆盖的整数,窗口外全部丢弃。算法从 lo 开始移动 cursor,遇到覆盖段前的空隙就输出,遇到覆盖段就把游标推过它,最后补上剩余尾巴。窗口左侧、右侧以及跨越窗口的覆盖都要分别考虑。

这里最值得审查的性质是双重有界补集等于原集合与窗口的交集,而不一定等于原集合本身;因为原集合在窗口外的信息已经被舍去。空窗口的补集为空,空集合在非空窗口中的补集是整个窗口。补集也必须与原集合不相交。示例同时覆盖这些条件,并让两个覆盖段刚好贴着窗口边界,防止把接触误当成覆盖。

独立文件:06_complement.mjs

import assert from "node:assert/strict";

function pair(value) {
  if (!Array.isArray(value) || value.length !== 2) {
    throw new TypeError("expected [bigint, bigint]");
  }
  const lo = value[0], hi = value[1];
  if (typeof lo !== "bigint" || typeof hi !== "bigint") {
    throw new TypeError("endpoints must be bigint");
  }
  if (lo > hi) throw new RangeError("reversed interval");
  return [lo, hi];
}
const cmp = (a, b) => a < b ? -1 : a > b ? 1 : 0;
function normalize(rows) {
  if (!Array.isArray(rows)) throw new TypeError("expected array");
  const copied = [];
  for (const row of rows) copied.push(pair(row));
  copied.sort((a, b) => cmp(a[0], b[0]) || cmp(a[1], b[1]));
  const out = [];
  for (const [lo, hi] of copied) {
    if (lo === hi) continue;
    const last = out.at(-1);
    if (!last || last[1] < lo) out.push([lo, hi]);
    else if (hi > last[1]) last[1] = hi;
  }
  return out;
}
function subtractOne(rows, [lo, hi]) {
  if (lo === hi) return rows;
  const out = [];
  for (const [a, b] of rows) {
    if (b <= lo || hi <= a) out.push([a, b]);
    else {
      if (a < lo) out.push([a, lo]);
      if (hi < b) out.push([hi, b]);
    }
  }
  return out;
}
class IntervalSet {
  #rows;
  constructor(rows = []) { this.#rows = normalize(rows); }
  static #fromCanonical(rows) {
    const result = new IntervalSet();
    result.#rows = rows;
    return result;
  }
  snapshot() { return this.#rows.map(([a, b]) => [a, b]); }
  has(x) {
    if (typeof x !== "bigint") throw new TypeError("expected bigint");
    return this.#rows.some(([a, b]) => a <= x && x < b);
  }
  add(...rows) {
    const next = normalize([...this.#rows, ...rows]);
    this.#rows = next;
    return this;
  }
  remove(...rows) {
    const cuts = normalize(rows);
    let next = this.snapshot();
    for (const cut of cuts) next = subtractOne(next, cut);
    this.#rows = next;
    return this;
  }
  intersection(other) {
    if (!(other instanceof IntervalSet)) throw new TypeError("expected IntervalSet");
    const a = this.#rows, b = other.#rows, out = [];
    let i = 0, j = 0;
    while (i < a.length && j < b.length) {
      const lo = a[i][0] > b[j][0] ? a[i][0] : b[j][0];
      const hi = a[i][1] < b[j][1] ? a[i][1] : b[j][1];
      if (lo < hi) out.push([lo, hi]);
      if (a[i][1] < b[j][1]) i++;
      else if (a[i][1] > b[j][1]) j++;
      else { i++; j++; }
    }
    return IntervalSet.#fromCanonical(out);
  }
  complementWithin(bounds) {
    const [lo, hi] = pair(bounds), out = [];
    let cursor = lo;
    for (const [a, b] of this.#rows) {
      if (b <= cursor) continue;
      if (a >= hi) break;
      if (cursor < a) out.push([cursor, a < hi ? a : hi]);
      if (b > cursor) cursor = b;
      if (cursor >= hi) break;
    }
    if (cursor < hi) out.push([cursor, hi]);
    return IntervalSet.#fromCanonical(out);
  }
}
const show = set => set.snapshot()
  .map(([a, b]) => `[${a},${b})`).join(" ") || "∅";

const set = new IntervalSet([[-9n, 2n], [4n, 7n], [9n, 30n]]);
const before = set.snapshot();
const gaps = set.complementWithin([0n, 12n]);
assert.deepEqual(gaps.snapshot(), [[2n, 4n], [7n, 9n]]);
assert.deepEqual(gaps.intersection(set).snapshot(), []);
assert.deepEqual(gaps.complementWithin([0n, 12n]).snapshot(),
  set.intersection(new IntervalSet([[0n, 12n]])).snapshot());
assert.deepEqual(set.complementWithin([5n, 5n]).snapshot(), []);
assert.deepEqual(set.complementWithin([50n, 55n]).snapshot(), [[50n, 55n]]);
assert.deepEqual(new IntervalSet().complementWithin([-3n, 3n]).snapshot(), [[-3n, 3n]]);
assert.deepEqual(new IntervalSet([[0n, 2n], [4n, 6n]])
  .complementWithin([2n, 4n]).snapshot(), [[2n, 4n]]);
assert.deepEqual(set.snapshot(), before);
console.log(show(gaps));
console.log("06 PASS: complement is clipped to its explicit bounds");

精确输出:

[2,4) [7,9)
06 PASS: complement is clipped to its explicit bounds

七、所有权与原子拒绝:异常之后也要断言状态

AI 常能生成抛出异常的校验,却漏掉异常发生前已经写入的数据。第七段故意把有效参数放在前面、非法参数放在后面,再分别调用批量添加和批量删除。每次断言异常类型之后,都立即比较当前快照与调用前快照。只检查 throws 是不够的:先改状态再抛错的版本同样会通过那个断言。

测试还修改构造输入、后续添加的输入以及返回快照的内层数组。只复制外层数组解决不了这个问题,因为里面的二元数组仍可能是同一个对象。BigInt 原始值本身不需要深复制,复制到二元数组这一层即可。本段覆盖八类非法区间以及两类非法查询调用,共二十六次拒绝检查;它验证的是此接口的状态隔离,不是在承诺任意 JavaScript 对象图都能安全克隆。

独立文件:07_atomic_ownership.mjs

import assert from "node:assert/strict";

function pair(value) {
  if (!Array.isArray(value) || value.length !== 2) {
    throw new TypeError("expected [bigint, bigint]");
  }
  const lo = value[0], hi = value[1];
  if (typeof lo !== "bigint" || typeof hi !== "bigint") {
    throw new TypeError("endpoints must be bigint");
  }
  if (lo > hi) throw new RangeError("reversed interval");
  return [lo, hi];
}
const cmp = (a, b) => a < b ? -1 : a > b ? 1 : 0;
function normalize(rows) {
  if (!Array.isArray(rows)) throw new TypeError("expected array");
  const copied = [];
  for (const row of rows) copied.push(pair(row));
  copied.sort((a, b) => cmp(a[0], b[0]) || cmp(a[1], b[1]));
  const out = [];
  for (const [lo, hi] of copied) {
    if (lo === hi) continue;
    const last = out.at(-1);
    if (!last || last[1] < lo) out.push([lo, hi]);
    else if (hi > last[1]) last[1] = hi;
  }
  return out;
}
function subtractOne(rows, [lo, hi]) {
  if (lo === hi) return rows;
  const out = [];
  for (const [a, b] of rows) {
    if (b <= lo || hi <= a) out.push([a, b]);
    else {
      if (a < lo) out.push([a, lo]);
      if (hi < b) out.push([hi, b]);
    }
  }
  return out;
}
class IntervalSet {
  #rows;
  constructor(rows = []) { this.#rows = normalize(rows); }
  static #fromCanonical(rows) {
    const result = new IntervalSet();
    result.#rows = rows;
    return result;
  }
  snapshot() { return this.#rows.map(([a, b]) => [a, b]); }
  has(x) {
    if (typeof x !== "bigint") throw new TypeError("expected bigint");
    return this.#rows.some(([a, b]) => a <= x && x < b);
  }
  add(...rows) {
    const next = normalize([...this.#rows, ...rows]);
    this.#rows = next;
    return this;
  }
  remove(...rows) {
    const cuts = normalize(rows);
    let next = this.snapshot();
    for (const cut of cuts) next = subtractOne(next, cut);
    this.#rows = next;
    return this;
  }
  intersection(other) {
    if (!(other instanceof IntervalSet)) throw new TypeError("expected IntervalSet");
    const a = this.#rows, b = other.#rows, out = [];
    let i = 0, j = 0;
    while (i < a.length && j < b.length) {
      const lo = a[i][0] > b[j][0] ? a[i][0] : b[j][0];
      const hi = a[i][1] < b[j][1] ? a[i][1] : b[j][1];
      if (lo < hi) out.push([lo, hi]);
      if (a[i][1] < b[j][1]) i++;
      else if (a[i][1] > b[j][1]) j++;
      else { i++; j++; }
    }
    return IntervalSet.#fromCanonical(out);
  }
  complementWithin(bounds) {
    const [lo, hi] = pair(bounds), out = [];
    let cursor = lo;
    for (const [a, b] of this.#rows) {
      if (b <= cursor) continue;
      if (a >= hi) break;
      if (cursor < a) out.push([cursor, a < hi ? a : hi]);
      if (b > cursor) cursor = b;
      if (cursor >= hi) break;
    }
    if (cursor < hi) out.push([cursor, hi]);
    return IntervalSet.#fromCanonical(out);
  }
}
const show = set => set.snapshot()
  .map(([a, b]) => `[${a},${b})`).join(" ") || "∅";

const input = [[0n, 10n]];
const set = new IntervalSet(input);
input[0][0] = -100n;
input.push([20n, 30n]);
const snap = set.snapshot();
snap[0][1] = 999n;
snap.push([50n, 60n]);
assert.deepEqual(set.snapshot(), [[0n, 10n]]);
const candidate = [20n, 30n];
set.add(candidate);
candidate[0] = -200n;
const before = set.snapshot();
const invalid = [null, [1n], [1n, 2n, 3n], [0, 1n],
  ["0", 1n], [Object(0n), 1n], [3n, 2n], new Array(2)];
for (const bad of invalid) {
  const error = Array.isArray(bad) && bad[0] === 3n ? RangeError : TypeError;
  assert.throws(() => set.add([40n, 50n], bad), error);
  assert.deepEqual(set.snapshot(), before);
  assert.throws(() => set.remove([2n, 8n], bad), error);
  assert.deepEqual(set.snapshot(), before);
  assert.throws(() => set.complementWithin(bad), error);
  assert.deepEqual(set.snapshot(), before);
}
assert.throws(() => set.has(1), TypeError);
assert.throws(() => set.intersection([]), TypeError);
assert.deepEqual(set.snapshot(), before);
assert.equal(set.add(), set);
assert.equal(set.remove(), set);
assert.deepEqual(set.snapshot(), before);
console.log("07 PASS: 26 rejected calls; no partial writes or leaked tuples");

精确输出:

07 PASS: 26 rejected calls; no partial writes or leaked tuples

八、巨大平移:小坐标正确还不够

只在零到十之间跑测试,即使内部偷偷把端点转换成 Number,也可能全部通过。我们把同一组输入整体平移十的八十次方,再执行添加、删除、求交和有界补集,最后把结果平移回来与小坐标结果比较。集合代数应与坐标原点无关;这个性质能够揭露隐藏的浮点化、位运算截断和固定宽度整数假设。即使坐标巨大,每段仍只保存两个端点,不枚举它覆盖的所有整数。

序列化是另一个独立边界。默认 JSON.stringify 不能直接处理本例的 BigInt 快照,见 ECMAScript SerializeJSONProperty。示例明确把二元端点编码成十进制字符串,再按已知结构还原;不改全局原型,也不把所有看起来像数字的字符串自动转换。这里测试的是本组件输出的往返,不是完整的不可信网络协议解析器。生产入口还要校验外层结构,并限制数组长度、字符串位数和资源使用。

独立文件:08_huge_translation.mjs

import assert from "node:assert/strict";

function pair(value) {
  if (!Array.isArray(value) || value.length !== 2) {
    throw new TypeError("expected [bigint, bigint]");
  }
  const lo = value[0], hi = value[1];
  if (typeof lo !== "bigint" || typeof hi !== "bigint") {
    throw new TypeError("endpoints must be bigint");
  }
  if (lo > hi) throw new RangeError("reversed interval");
  return [lo, hi];
}
const cmp = (a, b) => a < b ? -1 : a > b ? 1 : 0;
function normalize(rows) {
  if (!Array.isArray(rows)) throw new TypeError("expected array");
  const copied = [];
  for (const row of rows) copied.push(pair(row));
  copied.sort((a, b) => cmp(a[0], b[0]) || cmp(a[1], b[1]));
  const out = [];
  for (const [lo, hi] of copied) {
    if (lo === hi) continue;
    const last = out.at(-1);
    if (!last || last[1] < lo) out.push([lo, hi]);
    else if (hi > last[1]) last[1] = hi;
  }
  return out;
}
function subtractOne(rows, [lo, hi]) {
  if (lo === hi) return rows;
  const out = [];
  for (const [a, b] of rows) {
    if (b <= lo || hi <= a) out.push([a, b]);
    else {
      if (a < lo) out.push([a, lo]);
      if (hi < b) out.push([hi, b]);
    }
  }
  return out;
}
class IntervalSet {
  #rows;
  constructor(rows = []) { this.#rows = normalize(rows); }
  static #fromCanonical(rows) {
    const result = new IntervalSet();
    result.#rows = rows;
    return result;
  }
  snapshot() { return this.#rows.map(([a, b]) => [a, b]); }
  has(x) {
    if (typeof x !== "bigint") throw new TypeError("expected bigint");
    return this.#rows.some(([a, b]) => a <= x && x < b);
  }
  add(...rows) {
    const next = normalize([...this.#rows, ...rows]);
    this.#rows = next;
    return this;
  }
  remove(...rows) {
    const cuts = normalize(rows);
    let next = this.snapshot();
    for (const cut of cuts) next = subtractOne(next, cut);
    this.#rows = next;
    return this;
  }
  intersection(other) {
    if (!(other instanceof IntervalSet)) throw new TypeError("expected IntervalSet");
    const a = this.#rows, b = other.#rows, out = [];
    let i = 0, j = 0;
    while (i < a.length && j < b.length) {
      const lo = a[i][0] > b[j][0] ? a[i][0] : b[j][0];
      const hi = a[i][1] < b[j][1] ? a[i][1] : b[j][1];
      if (lo < hi) out.push([lo, hi]);
      if (a[i][1] < b[j][1]) i++;
      else if (a[i][1] > b[j][1]) j++;
      else { i++; j++; }
    }
    return IntervalSet.#fromCanonical(out);
  }
  complementWithin(bounds) {
    const [lo, hi] = pair(bounds), out = [];
    let cursor = lo;
    for (const [a, b] of this.#rows) {
      if (b <= cursor) continue;
      if (a >= hi) break;
      if (cursor < a) out.push([cursor, a < hi ? a : hi]);
      if (b > cursor) cursor = b;
      if (cursor >= hi) break;
    }
    if (cursor < hi) out.push([cursor, hi]);
    return IntervalSet.#fromCanonical(out);
  }
}
const show = set => set.snapshot()
  .map(([a, b]) => `[${a},${b})`).join(" ") || "∅";

const base = 10n ** 80n;
const rows = [[-5n, -2n], [0n, 4n], [8n, 9n]];
const shift = data => data.map(([a, b]) => [a + base, b + base]);
const unshift = data => data.map(([a, b]) => [a - base, b - base]);
const small = new IntervalSet(rows).add([4n, 6n]).remove([1n, 3n]);
const huge = new IntervalSet(shift(rows))
  .add([base + 4n, base + 6n]).remove([base + 1n, base + 3n]);
assert.deepEqual(unshift(huge.snapshot()), small.snapshot());
assert.deepEqual(unshift(huge.complementWithin([base - 6n, base + 10n]).snapshot()),
  small.complementWithin([-6n, 10n]).snapshot());
const window = [[-3n, 5n]];
assert.deepEqual(unshift(huge.intersection(new IntervalSet(shift(window))).snapshot()),
  small.intersection(new IntervalSet(window)).snapshot());
assert.throws(() => JSON.stringify(huge.snapshot()), TypeError);
const wire = JSON.stringify(huge.snapshot().map(row => row.map(String)));
const decoded = JSON.parse(wire).map(row => row.map(text => {
  assert.match(text, /^(0|-?[1-9][0-9]*)$/);
  return BigInt(text);
}));
assert.deepEqual(new IntervalSet(decoded).snapshot(), huge.snapshot());
console.log(show(small));
console.log("08 PASS: 10^80 translation and decimal-string round trip");

精确输出:

[-5,-2) [0,1) [3,6) [8,9)
08 PASS: 10^80 translation and decimal-string round trip

九、有限集合参考模型:用另一种表达方式验收

最后一个程序刻意不再用区间扫描实现答案,而是在只有六个整数的小域里,把每个坐标放入普通 Set。六个坐标共有六十四种子集,七个候选端点共有二十八个合法半开区间,包含七个空区间。程序枚举每种初始状态和每个区间的添加、删除、有界补集,再枚举两两状态的交集。两次相同的添加或删除用于验证幂等,完整结果逐点展开比较,同时检查规范表示没有空段、重叠或相接残留。

这种参考模型与生产实现采用不同的数据表示,降低同一个边界错误被复制两遍的风险。单步穷举之后,还有固定种子的连续一千二百步变更,检查状态累积是否偏离模型。这里输出的 mutations 统计的是添加与删除的测试场景,不是所有方法调用次数;每个场景实际调用相同操作两次。所有次数都由循环计算,不靠手写一个 PASS 来代替校验。

有限域穷举提供的是已覆盖域上的证据,不能证明任意规模实现永远正确,也不能代替性能测试。巨大端点的平移测试与有限域枚举承担不同职责:前者暴露数值表示退化,后者系统检查集合含义与边界组合。让 AI 同时满足两类证据,比仅要求更多随机样例更明确。

独立文件:09_finite_reference.mjs

import assert from "node:assert/strict";

function pair(value) {
  if (!Array.isArray(value) || value.length !== 2) {
    throw new TypeError("expected [bigint, bigint]");
  }
  const lo = value[0], hi = value[1];
  if (typeof lo !== "bigint" || typeof hi !== "bigint") {
    throw new TypeError("endpoints must be bigint");
  }
  if (lo > hi) throw new RangeError("reversed interval");
  return [lo, hi];
}
const cmp = (a, b) => a < b ? -1 : a > b ? 1 : 0;
function normalize(rows) {
  if (!Array.isArray(rows)) throw new TypeError("expected array");
  const copied = [];
  for (const row of rows) copied.push(pair(row));
  copied.sort((a, b) => cmp(a[0], b[0]) || cmp(a[1], b[1]));
  const out = [];
  for (const [lo, hi] of copied) {
    if (lo === hi) continue;
    const last = out.at(-1);
    if (!last || last[1] < lo) out.push([lo, hi]);
    else if (hi > last[1]) last[1] = hi;
  }
  return out;
}
function subtractOne(rows, [lo, hi]) {
  if (lo === hi) return rows;
  const out = [];
  for (const [a, b] of rows) {
    if (b <= lo || hi <= a) out.push([a, b]);
    else {
      if (a < lo) out.push([a, lo]);
      if (hi < b) out.push([hi, b]);
    }
  }
  return out;
}
class IntervalSet {
  #rows;
  constructor(rows = []) { this.#rows = normalize(rows); }
  static #fromCanonical(rows) {
    const result = new IntervalSet();
    result.#rows = rows;
    return result;
  }
  snapshot() { return this.#rows.map(([a, b]) => [a, b]); }
  has(x) {
    if (typeof x !== "bigint") throw new TypeError("expected bigint");
    return this.#rows.some(([a, b]) => a <= x && x < b);
  }
  add(...rows) {
    const next = normalize([...this.#rows, ...rows]);
    this.#rows = next;
    return this;
  }
  remove(...rows) {
    const cuts = normalize(rows);
    let next = this.snapshot();
    for (const cut of cuts) next = subtractOne(next, cut);
    this.#rows = next;
    return this;
  }
  intersection(other) {
    if (!(other instanceof IntervalSet)) throw new TypeError("expected IntervalSet");
    const a = this.#rows, b = other.#rows, out = [];
    let i = 0, j = 0;
    while (i < a.length && j < b.length) {
      const lo = a[i][0] > b[j][0] ? a[i][0] : b[j][0];
      const hi = a[i][1] < b[j][1] ? a[i][1] : b[j][1];
      if (lo < hi) out.push([lo, hi]);
      if (a[i][1] < b[j][1]) i++;
      else if (a[i][1] > b[j][1]) j++;
      else { i++; j++; }
    }
    return IntervalSet.#fromCanonical(out);
  }
  complementWithin(bounds) {
    const [lo, hi] = pair(bounds), out = [];
    let cursor = lo;
    for (const [a, b] of this.#rows) {
      if (b <= cursor) continue;
      if (a >= hi) break;
      if (cursor < a) out.push([cursor, a < hi ? a : hi]);
      if (b > cursor) cursor = b;
      if (cursor >= hi) break;
    }
    if (cursor < hi) out.push([cursor, hi]);
    return IntervalSet.#fromCanonical(out);
  }
}
const show = set => set.snapshot()
  .map(([a, b]) => `[${a},${b})`).join(" ") || "∅";

const domain = [-3n, -2n, -1n, 0n, 1n, 2n];
const key = values => [...values].sort(cmp).map(String).join(",");
function points(rows) {
  const out = new Set();
  for (const [a, b] of rows) for (let x = a; x < b; x++) out.add(x);
  return out;
}
function check(set, expected) {
  const rows = set.snapshot();
  for (let i = 0; i < rows.length; i++) {
    assert(rows[i][0] < rows[i][1]);
    if (i) assert(rows[i - 1][1] < rows[i][0]);
  }
  assert.equal(key(points(rows)), key(expected));
  for (const x of domain) assert.equal(set.has(x), expected.has(x));
}
const states = Array.from({length: 64}, (_, mask) => {
  const values = new Set(domain.filter((_, i) => mask & (1 << i)));
  const rows = [...values].map(x => [x, x + 1n]);
  return {values, rows};
});
const ranges = [];
for (let a = -3n; a <= 3n; a++)
  for (let b = a; b <= 3n; b++) ranges.push([a, b]);
let mutations = 0, intersections = 0, complements = 0;
for (const {values, rows} of states) {
  const original = new IntervalSet(rows);
  check(original, values);
  for (const range of ranges) {
    const covered = points([range]);
    const union = new Set([...values, ...covered]);
    const difference = new Set([...values].filter(x => !covered.has(x)));
    check(new IntervalSet(rows).add(range).add(range), union);
    check(new IntervalSet(rows).remove(range).remove(range), difference);
    mutations += 2;
    check(original.complementWithin(range),
      new Set([...covered].filter(x => !values.has(x))));
    complements++;
  }
  for (const other of states) {
    check(original.intersection(new IntervalSet(other.rows)),
      new Set([...values].filter(x => other.values.has(x))));
    intersections++;
  }
  assert.deepEqual(original.snapshot(), normalize(rows));
}
let seed = 20261019;
const random = n => { seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0; return seed % n; };
const live = new IntervalSet();
const model = new Set();
for (let step = 0; step < 1200; step++) {
  const range = ranges[random(ranges.length)];
  const adding = random(3) !== 0;
  if (adding) live.add(range); else live.remove(range);
  for (const x of points([range])) {
    if (adding) model.add(x); else model.delete(x);
  }
  check(live, model);
}
console.log(`states=64; mutations=${mutations}; intersections=${intersections}; complements=${complements}`);
console.log("09 PASS: exhaustive finite model and 1200 sequential operations");

精确输出:

states=64; mutations=3584; intersections=4096; complements=1792
09 PASS: exhaustive finite model and 1200 sequential operations

把这些结果变成真正的代码审查结论

先看接口是否把数据语义说清楚,再看每一条语义有没有对应失败反例。值得警惕的改动包括:把比较器改成 BigInt 差值;把相接合并条件换成小于等于;删除时对端点加减一;求交接受零宽输出;补集忘记窗口裁剪;批量操作边校验边写入;快照只拷贝外层。每个改动都很短,却可能分别破坏精度、规范表示、成员资格或状态隔离。

复杂度也要按实际代码说。设已有段数为 n、输入段数为 k,规范化排序通常按 O((n+k) log(n+k)) 的比较次数预算,但 ECMAScript 不保证具体排序算法的复杂度。当前批量删除先规范化切割区间并复制旧段,再逐个切割;按通常排序预算计,保守总计为 O(k log(k+1) + n + k(n+k)),无参数调用也有复制成本;求交双游标扫描为 O(n+m),有界补集和成员查询为 O(n)。这些计数把一次 BigInt 比较视为单位操作,巨大位数的真实成本并非恒定。高吞吐需求可再改成线性归并、二分索引或平衡树,正确性验收不应跟着重写。

最终交付给 AI 的改进请求应足够具体:保留 bigint 原始值契约、半开语义与相接规范化;任何写入先完成整批验证;继续通过手工边界、所有权、原子拒绝、巨大平移和有限参考模型五组证据。本文的组件没有数据库锁或事务语义,其价值是把一段看似显然的 JavaScript 集合代码,变成可以解释、复制运行并独立反驳的工程对象。

核验来源与复现说明

语言行为依据 ECMAScript 规范中的 BigInt 类型、数组排序比较和 JSON 序列化章节;断言与运行参数依据 Node.js 官方文档。区间 API、空区间策略、原子变更设计和参考模型是本文给出的组件契约,并非 JavaScript 内建 IntervalSet。所有示例在 Node.js v24.19.0 下以严格拒绝处理模式分别运行三次,输出逐字比对,不依赖网络、计时或异步竞态。

文章版权声明:除非注明,否则均为云鹊BLOG原创文章,转载或复制请以超链接形式并注明出处。