AI 代码审查实战:JavaScript Unicode 编辑距离与确定性编辑脚本
让 AI 写一个编辑距离函数,通常很快就能得到一段双重循环。真正值得审查的部分,却经常藏在循环之外:字符串中的一个字符到底是什么,多个最优答案选哪个,返回的下标能不能直接用于字符串切片,以及两个长输入会不会把服务线程堵住。只看到 kitten 到 sitting 的结果是三,并不足以判断实现可用。
本文从一个完整、有限的契约出发:按 Unicode 码点计算单位代价 Levenshtein 距离,并返回能够顺序回放的确定性编辑脚本。插入、删除、替换各记一分,保留相同码点记零分,不支持交换相邻字符这个额外操作。目标是短文本审查、纠错候选解释和测试工具;它不是现成的富文本补丁协议,也不把文字含义相近当作距离更小。
全文九个示例都可单独保存为 .cjs 文件,使用 Node.js v24.19.0 执行。实际测试命令为 node --unhandled-rejections=strict 文件名.cjs。每段都包含所需定义,不依赖上一个示例、网络请求或第三方包。为保证复制后就能运行,完整实现会重复出现;正式项目应把它集中到模块中,再由测试导入。

先写下不允许 AI 擅自改变的契约
默认 normalization 为 none,保持原始码点序列;显式传入 NFC 才先对两端做规范化。两种模式均拒绝包含孤立代理项的字符串,而不是悄悄替换成替代字符。输入只接受原始字符串,不把数字、对象或 String 包装对象自动转成文本。返回的 source 和 target 是实际参与比较的文本,脚本下标始终属于这两份文本。
资源策略也属于接口:每个原始输入最多四千零九十六个 UTF-16 码元,规范化后最多两千零四十八个码点;动态规划矩阵连同边界行列最多一百万格。先验证和计数,后分配矩阵。阈值不是性能保证,而是本文选择的拒绝边界;调用方应把超限当作明确失败处理,不能把失败伪装为距离零或一个大到含义不明的数字。
示例一:用最短反例拆穿字符单位混淆
JavaScript 的字符串长度与普通下标按 UTF-16 码元工作。补充平面里的笑脸需要两个码元,而字符串迭代器会把这一对组合成一个迭代项。ECMAScript 对这两类行为分别作了定义,因此同一个函数里如果一处使用字符串长度,另一处使用展开后的数组长度,边界通常就已经不一致。下面的断言让这个问题立即显形。来源:ECMAScript 字符串迭代器。
还要避免第二次偷换概念:码点不等于人眼看到的一个字。家庭表情包含七个码点,连字、组合附加符号和其他书写系统也可能涉及多个码点。字素簇分段是另一层规则;如果产品需求是按光标可移动的视觉字符比较,需要重新定义分词器和坐标含义,不能只给当前结果改个名字。来源:Unicode 文本分段规范。
示例还故意保留了一个不合法的孤立高代理项:迭代器能给出一个元素,并不代表它是有效的 Unicode 标量值。本文选择先拒绝这类输入,因此后续数组中的元素才都能作为有效单码点字符串使用。这个选择要在数据入口执行,不能寄希望于某个后续编码器自动修复。
'use strict';
const assert = require('node:assert/strict');
const face = '😀';
const family = '👨👩👧👦';
assert.equal(face.length, 2);
assert.equal(Array.from(face).length, 1);
assert.equal(Array.from(family).length, 7);
assert.equal('\uD800'.isWellFormed(), false);
assert.equal(Array.from('\uD800').length, 1);
console.log(JSON.stringify({ utf16: face.length,
codePoints: Array.from(face).length, familyPoints: Array.from(family).length }));实际输出:
{"utf16":2,"codePoints":1,"familyPoints":7}示例二:先验证距离定义,再讨论脚本
先看一个只返回数字的教学基线。行表示已经消费的源前缀,列表示已经形成的目标前缀;空前缀之间的转换由连续插入或删除完成。每一步比较删除、插入、对角线三种来源,对角线在码点相同时不收费,否则支付一次替换。上一行和当前行足以计算最终数值,但无法直接保存本文需要的整条重建路径。
这个问题的经典动态规划研究将编辑定义为单符号插入、删除和替换,并给出与两端长度乘积相关的算法。本文后面的完整版本采用后缀表,从右下角向左上角填表,以便从字符串开头按确定顺序输出脚本。两者计算同一种单位代价距离。原始论文:Wagner 与 Fischer,The String-to-String Correction Problem。
注意 ab 到 ba 的答案是二,交换不被算成一次操作。预组合的 é 与 e 加组合重音在不规范化时也不是同一序列:前者一个码点,后者两个码点,最少需要一次替换和一次插入。这些小例子比一组全是 ASCII 的常见单词更能发现需求被误读。基线只为短且合法的输入演示递推,不是对外使用的安全接口。
'use strict';
const assert = require('node:assert/strict');
// Teaching-only baseline: callers here supply short, well-formed strings.
function distance(a, b) {
const A = Array.from(a), B = Array.from(b);
let row = Array.from({ length: B.length + 1 }, (_, j) => j);
for (let i = 0; i < A.length; i++) {
const next = [i + 1];
for (let j = 0; j < B.length; j++) {
next[j + 1] = Math.min(row[j + 1] + 1, next[j] + 1,
row[j] + (A[i] === B[j] ? 0 : 1));
}
row = next;
}
return row[B.length];
}
assert.equal(distance('kitten', 'sitting'), 3);
assert.equal(distance('😀', ''), 1);
assert.equal(distance('ab', 'ba'), 2);
assert.equal(distance('é', 'e\u0301'), 2);
assert.equal(distance('', ''), 0);
console.log('baseline: 5 assertions passed');实际输出:
baseline: 5 assertions passed
示例三:用后缀距离表重建完整脚本
完整实现把 D[i,j] 定义为源序列从 i 开始的后缀与目标序列从 j 开始的后缀之间的距离。最后一列只剩删除,最后一行只剩插入;内部格子依赖右边、下边和右下角,所以必须倒序填充。重建从零开始,只有当某种操作的费用加上后继格子的最小费用等于当前格子时,才允许走这一步。
脚本中的 a 和 b 是操作开始前已经消费的源码点数、已经输出的目标码点数。keep 和 replace 都让两者加一,delete 只消费源,insert 只产生目标。每个事件统一包含 from 与 to,空字符串代表没有消费或没有输出。保留事件也明确记录,避免把隐含跳过的区间交给下游猜测;所以脚本长度不是编辑距离,非 keep 事件的数量才是距离。
为什么重建一定结束?每一步至少推进一个坐标,且不会越过各自终点,总步数不超过两端码点数之和。为什么费用最小?每一步保持当前最优值等于本步费用与剩余最优值之和,走到右下角后剩余费用为零。这里的证明约束比让 AI 再输出一句已经考虑所有边界更有价值,也能帮助审查者定位错误属于填表还是走表。
'use strict';
const assert = require('node:assert/strict');
function editDistance(source, target, normalization = 'none') {
if (normalization !== 'none' && normalization !== 'NFC') {
throw new RangeError('normalization must be none or NFC');
}
function prepare(value) {
if (typeof value !== 'string') throw new TypeError('string required');
if (value.length > 4096) throw new RangeError('UTF-16 limit');
if (!value.isWellFormed()) throw new TypeError('lone surrogate');
const text = normalization === 'NFC' ? value.normalize('NFC') : value;
const points = Array.from(text);
if (points.length > 2048) throw new RangeError('code-point limit');
return { text, points };
}
const left = prepare(source), right = prepare(target);
const A = left.points, B = right.points;
const m = A.length, n = B.length, width = n + 1;
const cells = (m + 1) * width;
if (cells > 1_000_000) throw new RangeError('matrix limit');
const D = new Uint16Array(cells);
const at = (i, j) => i * width + j;
for (let i = m; i >= 0; i--) D[at(i, n)] = m - i;
for (let j = n; j >= 0; j--) D[at(m, j)] = n - j;
for (let i = m - 1; i >= 0; i--) {
for (let j = n - 1; j >= 0; j--) {
D[at(i, j)] = Math.min(
D[at(i + 1, j + 1)] + (A[i] === B[j] ? 0 : 1),
D[at(i + 1, j)] + 1, D[at(i, j + 1)] + 1
);
}
}
const script = [];
let i = 0, j = 0;
while (i < m || j < n) {
const cost = D[at(i, j)];
if (i < m && j < n && A[i] === B[j] &&
cost === D[at(i + 1, j + 1)]) {
script.push({ op: 'keep', a: i, b: j, from: A[i], to: B[j] });
i++; j++;
} else if (i < m && j < n && A[i] !== B[j] &&
cost === D[at(i + 1, j + 1)] + 1) {
script.push({ op: 'replace', a: i, b: j, from: A[i], to: B[j] });
i++; j++;
} else if (i < m && cost === D[at(i + 1, j)] + 1) {
script.push({ op: 'delete', a: i, b: j, from: A[i], to: '' });
i++;
} else if (j < n && cost === D[at(i, j + 1)] + 1) {
script.push({ op: 'insert', a: i, b: j, from: '', to: B[j] });
j++;
} else {
throw new Error('broken reconstruction invariant');
}
}
return { distance: D[0], source: left.text, target: right.text, script };
}
const result = editDistance('kitten', 'sitting');
assert.equal(result.distance, 3);
assert.deepEqual(result.script.map(x => x.op),
['replace', 'keep', 'keep', 'keep', 'replace', 'keep', 'insert']);
assert.equal(result.script.map(x => x.to).join(''), 'sitting');
console.log(JSON.stringify({ distance: result.distance,
operations: result.script.map(x => x.op) }));实际输出:
{"distance":3,"operations":["replace","keep","keep","keep","replace","keep","insert"]}示例四:把平局规则变成可测试的输出契约
距离唯一并不代表脚本唯一。ab 到 ba 可以替换两次,也可以删除开头再保留并插入;aa 到 a 又有两个位置可以删除。若依赖数组排序的偶然顺序,换一次重构就可能改变高亮位置,导致快照测试、审计记录和用户看到的解释不断漂移。
本文在从左到右重建的每个状态上,固定尝试 keep、replace、delete、insert,并只接受仍能达到最小费用的操作。因此这是一条面向当前最优后继的优先规则,不能表述为先执行全局所有替换。相等时先保留,意味着重复字符通常保留更早的匹配;两个不同字符互换时,replace 的优先级使输出稳定为两次替换。
对字符串对调方向,距离应保持不变,但确定性脚本不承诺正好是原脚本倒放。删除与插入的优先关系有方向性,坐标也归属于不同文本。产品如果需要双向补丁一致性,必须另外定义规则并测试,而不是从距离的对称性推导出脚本也有相同性质。下面的例子只锁定本文承诺的确定顺序和重复执行结果。
'use strict';
const assert = require('node:assert/strict');
function editDistance(source, target, normalization = 'none') {
if (normalization !== 'none' && normalization !== 'NFC') {
throw new RangeError('normalization must be none or NFC');
}
function prepare(value) {
if (typeof value !== 'string') throw new TypeError('string required');
if (value.length > 4096) throw new RangeError('UTF-16 limit');
if (!value.isWellFormed()) throw new TypeError('lone surrogate');
const text = normalization === 'NFC' ? value.normalize('NFC') : value;
const points = Array.from(text);
if (points.length > 2048) throw new RangeError('code-point limit');
return { text, points };
}
const left = prepare(source), right = prepare(target);
const A = left.points, B = right.points;
const m = A.length, n = B.length, width = n + 1;
const cells = (m + 1) * width;
if (cells > 1_000_000) throw new RangeError('matrix limit');
const D = new Uint16Array(cells);
const at = (i, j) => i * width + j;
for (let i = m; i >= 0; i--) D[at(i, n)] = m - i;
for (let j = n; j >= 0; j--) D[at(m, j)] = n - j;
for (let i = m - 1; i >= 0; i--) {
for (let j = n - 1; j >= 0; j--) {
D[at(i, j)] = Math.min(
D[at(i + 1, j + 1)] + (A[i] === B[j] ? 0 : 1),
D[at(i + 1, j)] + 1, D[at(i, j + 1)] + 1
);
}
}
const script = [];
let i = 0, j = 0;
while (i < m || j < n) {
const cost = D[at(i, j)];
if (i < m && j < n && A[i] === B[j] &&
cost === D[at(i + 1, j + 1)]) {
script.push({ op: 'keep', a: i, b: j, from: A[i], to: B[j] });
i++; j++;
} else if (i < m && j < n && A[i] !== B[j] &&
cost === D[at(i + 1, j + 1)] + 1) {
script.push({ op: 'replace', a: i, b: j, from: A[i], to: B[j] });
i++; j++;
} else if (i < m && cost === D[at(i + 1, j)] + 1) {
script.push({ op: 'delete', a: i, b: j, from: A[i], to: '' });
i++;
} else if (j < n && cost === D[at(i, j + 1)] + 1) {
script.push({ op: 'insert', a: i, b: j, from: '', to: B[j] });
j++;
} else {
throw new Error('broken reconstruction invariant');
}
}
return { distance: D[0], source: left.text, target: right.text, script };
}
const cases = [
['ab', 'ba', ['replace', 'replace']],
['aa', 'a', ['keep', 'delete']],
['a', 'aa', ['keep', 'insert']],
['', '😀', ['insert']],
['😀', '', ['delete']]
];
for (const [a, b, expected] of cases) {
const result = editDistance(a, b);
assert.deepEqual(result.script.map(x => x.op), expected);
assert.deepEqual(result, editDistance(a, b));
}
console.log('stable tie order: 5 cases passed');实际输出:
stable tie order: 5 cases passed
示例五:规范化与非法编码都必须显式决定
NFC 用规范等价关系处理可组合的字符序列,并不等于把一切长得相似的符号统一。它也不会自动忽略大小写、空白或所有全角差异。因此本文同时测试 é 的规范等价和全角A与 A 的保留差异。选择 NFC 会改变参与计算的序列,返回值必须把实际 source、target 一并给出,便于调用方知道零距离究竟是在何种预处理后得到的。来源:Unicode 规范化形式。
默认 none 是刻意保守的选择:文本审计可能关心原始输入是否发生变化,而搜索框可能更愿意把规范等价文本合并。两种业务都合理,不能由实现猜测。在 NFC 模式下,原始文本不同但距离为零是预期结果;若需要把高亮映射回原始 UTF-16 偏移,还要维护规范化前后的映射,本实现没有提供这一额外能力。
孤立代理项则在规范化之前就被拒绝。直接调用 toWellFormed 会将有问题的码元改成替代字符,多个不同损坏输入可能因此失去差异;这对需要原样审计的工具不合适。合法的 U+FFFD 本身仍可参与比较,不能和不合法代理项一并拒绝。isWellFormed 用来检测合法性,这个检测不意味着实施内容过滤。来源:ECMAScript isWellFormed。
'use strict';
const assert = require('node:assert/strict');
function editDistance(source, target, normalization = 'none') {
if (normalization !== 'none' && normalization !== 'NFC') {
throw new RangeError('normalization must be none or NFC');
}
function prepare(value) {
if (typeof value !== 'string') throw new TypeError('string required');
if (value.length > 4096) throw new RangeError('UTF-16 limit');
if (!value.isWellFormed()) throw new TypeError('lone surrogate');
const text = normalization === 'NFC' ? value.normalize('NFC') : value;
const points = Array.from(text);
if (points.length > 2048) throw new RangeError('code-point limit');
return { text, points };
}
const left = prepare(source), right = prepare(target);
const A = left.points, B = right.points;
const m = A.length, n = B.length, width = n + 1;
const cells = (m + 1) * width;
if (cells > 1_000_000) throw new RangeError('matrix limit');
const D = new Uint16Array(cells);
const at = (i, j) => i * width + j;
for (let i = m; i >= 0; i--) D[at(i, n)] = m - i;
for (let j = n; j >= 0; j--) D[at(m, j)] = n - j;
for (let i = m - 1; i >= 0; i--) {
for (let j = n - 1; j >= 0; j--) {
D[at(i, j)] = Math.min(
D[at(i + 1, j + 1)] + (A[i] === B[j] ? 0 : 1),
D[at(i + 1, j)] + 1, D[at(i, j + 1)] + 1
);
}
}
const script = [];
let i = 0, j = 0;
while (i < m || j < n) {
const cost = D[at(i, j)];
if (i < m && j < n && A[i] === B[j] &&
cost === D[at(i + 1, j + 1)]) {
script.push({ op: 'keep', a: i, b: j, from: A[i], to: B[j] });
i++; j++;
} else if (i < m && j < n && A[i] !== B[j] &&
cost === D[at(i + 1, j + 1)] + 1) {
script.push({ op: 'replace', a: i, b: j, from: A[i], to: B[j] });
i++; j++;
} else if (i < m && cost === D[at(i + 1, j)] + 1) {
script.push({ op: 'delete', a: i, b: j, from: A[i], to: '' });
i++;
} else if (j < n && cost === D[at(i, j + 1)] + 1) {
script.push({ op: 'insert', a: i, b: j, from: '', to: B[j] });
j++;
} else {
throw new Error('broken reconstruction invariant');
}
}
return { distance: D[0], source: left.text, target: right.text, script };
}
const raw = editDistance('é', 'e\u0301');
const nfc = editDistance('é', 'e\u0301', 'NFC');
assert.equal(raw.distance, 2);
assert.equal(nfc.distance, 0);
assert.equal(nfc.target, 'é');
assert.equal(nfc.script.length, 1);
assert.equal(editDistance('👨👩👧👦', '').distance, 7);
assert.equal(editDistance('A', 'A', 'NFC').distance, 1);
for (const bad of ['\uD800', '\uDC00', 'a\uD800b']) {
for (const mode of ['none', 'NFC']) {
assert.throws(() => editDistance(bad, '', mode), TypeError);
}
}
assert.equal(editDistance('\uFFFD', '').distance, 1);
console.log(JSON.stringify({ raw: raw.distance, NFC: nfc.distance,
family: 7, rejectedMalformed: 6 }));实际输出:
{"raw":2,"NFC":0,"family":7,"rejectedMalformed":6}示例六:独立回放器检验坐标与操作含义
只检查所有 to 拼接后等于目标仍然不够:一个脚本可以漏读源字符,也可以带着错误的坐标碰巧输出正确文本。回放器要同时检查输入消费顺序、输出位置、from 是否匹配当前源字符,以及不同操作应该具有的空字段和非空字段。keep 要求两端相等,replace 要求不同,最后还必须确认源全部消费完。
这里的回放器不读取动态规划表,也不调用求解器去解释事件。它按公开协议逐步执行,把最终文本和实际费用一起返回。这样的分离能捕获重建器与调用方对坐标单位理解不一致的问题。示例中的笑脸在数组中只占一个位置,但后面的 a 在原始 JavaScript 字符串中从偏移二开始;将码点下标直接交给字符串切片会切错位置。
我们还手动篡改一个事件的 a,要求回放失败。负向测试证明断言确实覆盖了坐标,而不只是重复正向示例。请把这个回放器看作可信测试输入上的协议检查工具;它不是接收恶意外部补丁的完整安全解析器。若脚本来自网络,还需要限制事件数量、验证外层结构、隔离异常并处理输入来源授权。
'use strict';
const assert = require('node:assert/strict');
function editDistance(source, target, normalization = 'none') {
if (normalization !== 'none' && normalization !== 'NFC') {
throw new RangeError('normalization must be none or NFC');
}
function prepare(value) {
if (typeof value !== 'string') throw new TypeError('string required');
if (value.length > 4096) throw new RangeError('UTF-16 limit');
if (!value.isWellFormed()) throw new TypeError('lone surrogate');
const text = normalization === 'NFC' ? value.normalize('NFC') : value;
const points = Array.from(text);
if (points.length > 2048) throw new RangeError('code-point limit');
return { text, points };
}
const left = prepare(source), right = prepare(target);
const A = left.points, B = right.points;
const m = A.length, n = B.length, width = n + 1;
const cells = (m + 1) * width;
if (cells > 1_000_000) throw new RangeError('matrix limit');
const D = new Uint16Array(cells);
const at = (i, j) => i * width + j;
for (let i = m; i >= 0; i--) D[at(i, n)] = m - i;
for (let j = n; j >= 0; j--) D[at(m, j)] = n - j;
for (let i = m - 1; i >= 0; i--) {
for (let j = n - 1; j >= 0; j--) {
D[at(i, j)] = Math.min(
D[at(i + 1, j + 1)] + (A[i] === B[j] ? 0 : 1),
D[at(i + 1, j)] + 1, D[at(i, j + 1)] + 1
);
}
}
const script = [];
let i = 0, j = 0;
while (i < m || j < n) {
const cost = D[at(i, j)];
if (i < m && j < n && A[i] === B[j] &&
cost === D[at(i + 1, j + 1)]) {
script.push({ op: 'keep', a: i, b: j, from: A[i], to: B[j] });
i++; j++;
} else if (i < m && j < n && A[i] !== B[j] &&
cost === D[at(i + 1, j + 1)] + 1) {
script.push({ op: 'replace', a: i, b: j, from: A[i], to: B[j] });
i++; j++;
} else if (i < m && cost === D[at(i + 1, j)] + 1) {
script.push({ op: 'delete', a: i, b: j, from: A[i], to: '' });
i++;
} else if (j < n && cost === D[at(i, j + 1)] + 1) {
script.push({ op: 'insert', a: i, b: j, from: '', to: B[j] });
j++;
} else {
throw new Error('broken reconstruction invariant');
}
}
return { distance: D[0], source: left.text, target: right.text, script };
}
function replay(source, script) {
const A = Array.from(source), output = [];
let i = 0, cost = 0;
const one = s => typeof s === 'string' && s.isWellFormed() &&
Array.from(s).length === 1;
for (const step of script) {
assert.equal(step.a, i);
assert.equal(step.b, output.length);
assert.ok(['keep', 'replace', 'delete', 'insert'].includes(step.op));
if (step.op !== 'insert') {
assert.ok(i < A.length);
assert.equal(step.from, A[i++]);
} else assert.equal(step.from, '');
if (step.op !== 'delete') {
assert.ok(one(step.to));
output.push(step.to);
} else assert.equal(step.to, '');
if (step.op === 'keep') assert.equal(step.from, step.to);
else {
cost++;
if (step.op === 'replace') assert.notEqual(step.from, step.to);
}
}
assert.equal(i, A.length);
return { text: output.join(''), cost };
}
const result = editDistance('😀ab', '😀中b!');
assert.deepEqual(replay(result.source, result.script),
{ text: result.target, cost: result.distance });
assert.equal(result.script[1].a, 1);
assert.equal(result.source.indexOf('a'), 2);
const tampered = structuredClone(result.script);
tampered[1].a = 2;
assert.throws(() => replay(result.source, tampered));
console.log(JSON.stringify({ rebuilt: result.target, distance: result.distance,
replacementCodePointIndex: 1, utf16Index: 2, tamperRejected: true }));实际输出:
{"rebuilt":"😀中b!","distance":2,"replacementCodePointIndex":1,"utf16Index":2,"tamperRejected":true}示例七:不用同一个递推再写一遍参考答案
把动态规划从二维数组改成 Map,通常只是同一个想法的另一种写法,不能很好地避免共同错误。这里的独立 oracle 把完整字符串当作图的顶点,任意一次插入、删除或替换当作一条等权边。广度优先搜索第一次到达某个字符串时的层数,就是从起点到它所需的最少编辑次数;代码没有使用前缀或后缀距离递推。
测试字母表只有 a、b 和笑脸,最大长度为三,总共四十个字符串。对每个起点完成一次搜索,再比较所有终点,得到一千六百组穷举验证。搜索只包含这三个符号且不超过三的字符串是有理由的:对于本例的单位代价编辑,存在一条最优对齐;先做其中的删除,再替换,最后插入,就不必引入目标和源以外的符号,也不必让中间长度超过两端长度的较大值。
这份 oracle 故意只服务于小规模测试,不能替代生产算法。状态数会随长度呈指数增长,把上限从三随意改成几十会非常危险。它的价值是尽量使用不同机制验证最小费用,再用回放器验证脚本确实达到该费用。穷举通过不等于数学上证明全部 Unicode 输入正确,但它能提供比少量手写答案更密集的反例搜索。
'use strict';
const assert = require('node:assert/strict');
function editDistance(source, target, normalization = 'none') {
if (normalization !== 'none' && normalization !== 'NFC') {
throw new RangeError('normalization must be none or NFC');
}
function prepare(value) {
if (typeof value !== 'string') throw new TypeError('string required');
if (value.length > 4096) throw new RangeError('UTF-16 limit');
if (!value.isWellFormed()) throw new TypeError('lone surrogate');
const text = normalization === 'NFC' ? value.normalize('NFC') : value;
const points = Array.from(text);
if (points.length > 2048) throw new RangeError('code-point limit');
return { text, points };
}
const left = prepare(source), right = prepare(target);
const A = left.points, B = right.points;
const m = A.length, n = B.length, width = n + 1;
const cells = (m + 1) * width;
if (cells > 1_000_000) throw new RangeError('matrix limit');
const D = new Uint16Array(cells);
const at = (i, j) => i * width + j;
for (let i = m; i >= 0; i--) D[at(i, n)] = m - i;
for (let j = n; j >= 0; j--) D[at(m, j)] = n - j;
for (let i = m - 1; i >= 0; i--) {
for (let j = n - 1; j >= 0; j--) {
D[at(i, j)] = Math.min(
D[at(i + 1, j + 1)] + (A[i] === B[j] ? 0 : 1),
D[at(i + 1, j)] + 1, D[at(i, j + 1)] + 1
);
}
}
const script = [];
let i = 0, j = 0;
while (i < m || j < n) {
const cost = D[at(i, j)];
if (i < m && j < n && A[i] === B[j] &&
cost === D[at(i + 1, j + 1)]) {
script.push({ op: 'keep', a: i, b: j, from: A[i], to: B[j] });
i++; j++;
} else if (i < m && j < n && A[i] !== B[j] &&
cost === D[at(i + 1, j + 1)] + 1) {
script.push({ op: 'replace', a: i, b: j, from: A[i], to: B[j] });
i++; j++;
} else if (i < m && cost === D[at(i + 1, j)] + 1) {
script.push({ op: 'delete', a: i, b: j, from: A[i], to: '' });
i++;
} else if (j < n && cost === D[at(i, j + 1)] + 1) {
script.push({ op: 'insert', a: i, b: j, from: '', to: B[j] });
j++;
} else {
throw new Error('broken reconstruction invariant');
}
}
return { distance: D[0], source: left.text, target: right.text, script };
}
function replay(source, script) {
const A = Array.from(source), output = [];
let i = 0, cost = 0;
const one = s => typeof s === 'string' && s.isWellFormed() &&
Array.from(s).length === 1;
for (const step of script) {
assert.equal(step.a, i);
assert.equal(step.b, output.length);
assert.ok(['keep', 'replace', 'delete', 'insert'].includes(step.op));
if (step.op !== 'insert') {
assert.ok(i < A.length);
assert.equal(step.from, A[i++]);
} else assert.equal(step.from, '');
if (step.op !== 'delete') {
assert.ok(one(step.to));
output.push(step.to);
} else assert.equal(step.to, '');
if (step.op === 'keep') assert.equal(step.from, step.to);
else {
cost++;
if (step.op === 'replace') assert.notEqual(step.from, step.to);
}
}
assert.equal(i, A.length);
return { text: output.join(''), cost };
}
// Independent oracle: breadth-first search in the graph of whole strings.
function graphDistances(start, alphabet, maxLength) {
const distances = new Map([[start, 0]]), queue = [start];
for (let head = 0; head < queue.length; head++) {
const text = queue[head], A = Array.from(text);
const visit = next => {
const s = next.join('');
if (!distances.has(s)) {
distances.set(s, distances.get(text) + 1);
queue.push(s);
}
};
for (let i = 0; i < A.length; i++) {
visit([...A.slice(0, i), ...A.slice(i + 1)]);
for (const c of alphabet) {
visit([...A.slice(0, i), c, ...A.slice(i + 1)]);
}
}
if (A.length < maxLength) {
for (let i = 0; i <= A.length; i++) {
for (const c of alphabet) visit([...A.slice(0, i), c, ...A.slice(i)]);
}
}
}
return distances;
}
const alphabet = ['a', 'b', '😀'];
const words = [''];
for (let i = 0; i < words.length; i++) {
if (Array.from(words[i]).length < 3) {
for (const c of alphabet) words.push(words[i] + c);
}
}
let checked = 0;
for (const a of words) {
const expected = graphDistances(a, alphabet, 3);
assert.equal(expected.size, 40);
for (const b of words) {
const result = editDistance(a, b);
assert.equal(result.distance, expected.get(b), JSON.stringify([a, b]));
assert.deepEqual(replay(result.source, result.script),
{ text: result.target, cost: expected.get(b) });
checked++;
}
}
console.log(`independent BFS oracle: ${checked} pairs passed`);实际输出:
independent BFS oracle: 1600 pairs passed
示例八:用固定种子的性质测试补足组合空间
穷举覆盖所有短字符串,随机性质测试则扩大符号和长度组合。本例加入中文、补充平面字符、预组合重音和独立组合符,使用固定种子产生五百组三元输入。固定种子让失败能在相同运行时稳定重现;它不表示采样在统计上完美均匀,也不是加密随机数,测试结束后应把任何发现的反例单独加入回归集合。
我们检验对称性、长度差下界、较大长度上界和三角不等式,同时检查脚本的源投影、目标投影以及非保留事件计数。长度差下界来自每次插入或删除最多改变一个码点数量;上界来自先逐位替换重叠部分,再补齐长度差。这些性质来自本文自己的单位代价契约,不依赖某个词库中的特定答案。
性质测试与独立 oracle 是互补关系。一个始终返回两端长度之和的错误实现可能通过某些弱性质,所以不能只靠看上去数学味很重的断言。另一方面,oracle 的小字母表也不会自动验证规范化、资源限制或运行时输入类型。审查计划应把每种测试和它要守住的承诺对应起来,避免把测试数量当成覆盖范围。
'use strict';
const assert = require('node:assert/strict');
function editDistance(source, target, normalization = 'none') {
if (normalization !== 'none' && normalization !== 'NFC') {
throw new RangeError('normalization must be none or NFC');
}
function prepare(value) {
if (typeof value !== 'string') throw new TypeError('string required');
if (value.length > 4096) throw new RangeError('UTF-16 limit');
if (!value.isWellFormed()) throw new TypeError('lone surrogate');
const text = normalization === 'NFC' ? value.normalize('NFC') : value;
const points = Array.from(text);
if (points.length > 2048) throw new RangeError('code-point limit');
return { text, points };
}
const left = prepare(source), right = prepare(target);
const A = left.points, B = right.points;
const m = A.length, n = B.length, width = n + 1;
const cells = (m + 1) * width;
if (cells > 1_000_000) throw new RangeError('matrix limit');
const D = new Uint16Array(cells);
const at = (i, j) => i * width + j;
for (let i = m; i >= 0; i--) D[at(i, n)] = m - i;
for (let j = n; j >= 0; j--) D[at(m, j)] = n - j;
for (let i = m - 1; i >= 0; i--) {
for (let j = n - 1; j >= 0; j--) {
D[at(i, j)] = Math.min(
D[at(i + 1, j + 1)] + (A[i] === B[j] ? 0 : 1),
D[at(i + 1, j)] + 1, D[at(i, j + 1)] + 1
);
}
}
const script = [];
let i = 0, j = 0;
while (i < m || j < n) {
const cost = D[at(i, j)];
if (i < m && j < n && A[i] === B[j] &&
cost === D[at(i + 1, j + 1)]) {
script.push({ op: 'keep', a: i, b: j, from: A[i], to: B[j] });
i++; j++;
} else if (i < m && j < n && A[i] !== B[j] &&
cost === D[at(i + 1, j + 1)] + 1) {
script.push({ op: 'replace', a: i, b: j, from: A[i], to: B[j] });
i++; j++;
} else if (i < m && cost === D[at(i + 1, j)] + 1) {
script.push({ op: 'delete', a: i, b: j, from: A[i], to: '' });
i++;
} else if (j < n && cost === D[at(i, j + 1)] + 1) {
script.push({ op: 'insert', a: i, b: j, from: '', to: B[j] });
j++;
} else {
throw new Error('broken reconstruction invariant');
}
}
return { distance: D[0], source: left.text, target: right.text, script };
}
let state = 0x5eed1234;
function random(n) {
state = (Math.imul(state, 1664525) + 1013904223) >>> 0;
return state % n;
}
const alphabet = ['a', 'b', '中', '😀', '\u0301', 'é'];
function word() {
const length = random(9);
let s = '';
for (let i = 0; i < length; i++) s += alphabet[random(alphabet.length)];
return s;
}
for (let k = 0; k < 500; k++) {
const a = word(), b = word(), c = word();
const ab = editDistance(a, b), ba = editDistance(b, a);
const m = Array.from(a).length, n = Array.from(b).length;
assert.equal(ab.distance, ba.distance);
assert.ok(ab.distance >= Math.abs(m - n));
assert.ok(ab.distance <= Math.max(m, n));
assert.ok(ab.distance <= editDistance(a, c).distance + editDistance(c, b).distance);
assert.equal(ab.script.map(x => x.from).join(''), a);
assert.equal(ab.script.map(x => x.to).join(''), b);
assert.equal(ab.script.filter(x => x.op !== 'keep').length, ab.distance);
assert.deepEqual(ab, editDistance(a, b));
}
console.log('seeded properties: 500 triples passed');实际输出:
seeded properties: 500 triples passed
示例九:让资源边界也进入回归测试
完整表的时间与空间都按两个长度的乘积增长,边界行列也要占空间。九百九十九对九百九十九会分配恰好一百万格,而一千对九百九十九已经超限。矩阵用 Uint16Array,每格两个字节,载荷最多二百万字节;总进程内存还包括输入、数组、脚本对象和运行时开销,不能把矩阵载荷写成整个请求的内存上限。
十六位无符号整数能够容纳费用,是因为每端最多两千零四十八个码点,而单位代价距离不会大于两端较大长度。这是类型选择依赖的证明条件。如果以后把代价改成可配置权重,或提高长度阈值,就必须重新检查数值范围。简单换成更大数组类型也不能解除二次复杂度带来的成本。
检查原始码元数在规范化之前,可以先挡住巨大输入;规范化之后仍要重新检查码点数,因为 NFC 不保证长度只减不增。示例用组合分音符与锐音符的组合字符展示这种扩张。矩阵检查发生在输入检查之后,即便两端完全相等,超限输入仍按同一契约拒绝,不通过快捷路径偷偷绕过资源规则。
这些阈值约束单次同步计算,并不负责并发请求的总预算。大量请求同时到来时,服务仍需要限流、工作线程隔离或可取消的任务调度。如果只要距离,可以考虑滚动行;若需要巨量文本的脚本,则应重新评估算法与输出协议。任何优化都应先保留这里的坐标、平局和预处理承诺,再用相同测试证明没有改变行为。
'use strict';
const assert = require('node:assert/strict');
function editDistance(source, target, normalization = 'none') {
if (normalization !== 'none' && normalization !== 'NFC') {
throw new RangeError('normalization must be none or NFC');
}
function prepare(value) {
if (typeof value !== 'string') throw new TypeError('string required');
if (value.length > 4096) throw new RangeError('UTF-16 limit');
if (!value.isWellFormed()) throw new TypeError('lone surrogate');
const text = normalization === 'NFC' ? value.normalize('NFC') : value;
const points = Array.from(text);
if (points.length > 2048) throw new RangeError('code-point limit');
return { text, points };
}
const left = prepare(source), right = prepare(target);
const A = left.points, B = right.points;
const m = A.length, n = B.length, width = n + 1;
const cells = (m + 1) * width;
if (cells > 1_000_000) throw new RangeError('matrix limit');
const D = new Uint16Array(cells);
const at = (i, j) => i * width + j;
for (let i = m; i >= 0; i--) D[at(i, n)] = m - i;
for (let j = n; j >= 0; j--) D[at(m, j)] = n - j;
for (let i = m - 1; i >= 0; i--) {
for (let j = n - 1; j >= 0; j--) {
D[at(i, j)] = Math.min(
D[at(i + 1, j + 1)] + (A[i] === B[j] ? 0 : 1),
D[at(i + 1, j)] + 1, D[at(i, j + 1)] + 1
);
}
}
const script = [];
let i = 0, j = 0;
while (i < m || j < n) {
const cost = D[at(i, j)];
if (i < m && j < n && A[i] === B[j] &&
cost === D[at(i + 1, j + 1)]) {
script.push({ op: 'keep', a: i, b: j, from: A[i], to: B[j] });
i++; j++;
} else if (i < m && j < n && A[i] !== B[j] &&
cost === D[at(i + 1, j + 1)] + 1) {
script.push({ op: 'replace', a: i, b: j, from: A[i], to: B[j] });
i++; j++;
} else if (i < m && cost === D[at(i + 1, j)] + 1) {
script.push({ op: 'delete', a: i, b: j, from: A[i], to: '' });
i++;
} else if (j < n && cost === D[at(i, j + 1)] + 1) {
script.push({ op: 'insert', a: i, b: j, from: '', to: B[j] });
j++;
} else {
throw new Error('broken reconstruction invariant');
}
}
return { distance: D[0], source: left.text, target: right.text, script };
}
assert.equal(editDistance('a'.repeat(999), 'b'.repeat(999)).distance, 999);
assert.throws(() => editDistance('a'.repeat(1000), 'b'.repeat(999)),
{ name: 'RangeError', message: 'matrix limit' });
assert.equal(editDistance('😀'.repeat(2048), '').distance, 2048);
assert.throws(() => editDistance('a'.repeat(2049), ''),
{ name: 'RangeError', message: 'code-point limit' });
assert.throws(() => editDistance('a'.repeat(4097), ''),
{ name: 'RangeError', message: 'UTF-16 limit' });
// NFC may expand a code point, so the post-normalization cap matters.
assert.throws(() => editDistance('\u0344'.repeat(1025), '', 'NFC'),
{ name: 'RangeError', message: 'code-point limit' });
for (const bad of [null, 7, {}, new String('a')]) {
assert.throws(() => editDistance(bad, ''), TypeError);
}
for (const bad of [null, false, 'NFD', 'NFKC', 'nfc']) {
assert.throws(() => editDistance('', '', bad), RangeError);
}
console.log('resource and input boundaries: 15 assertions passed');实际输出:
resource and input boundaries: 15 assertions passed
把这套方法变成 AI 审查清单
给 AI 的任务不应只有实现 Levenshtein 距离这一句话。更有用的约束是:先解释字符串单位与合法输入集合,写明规范化是否改变坐标,给出最小费用与确定脚本两个独立承诺,指出分配矩阵之前执行的拒绝条件,最后提交能推翻自己实现的反例。让它逐条说明每个断言保护哪一条承诺,比让它评价代码是否健壮更容易核对。
复核时也应避免只问能否再优化。先看空串和重复字符是否处理一致,再看补充平面字符有没有被拆开,之后核对脚本能否独立消费整个源并形成目标,最后检查超限是否明确失败。若一项改动导致平局脚本变化,即使距离全部正确,也应当被视为输出契约变更,由产品与调用方决定是否接受。
本文的最终交付不是一个神奇的距离数字,而是一套可解释的边界:比较什么、拒绝什么、如何选择最优答案,以及如何用不同机制检查结果。AI 可以帮助迅速生成实现和反例,人仍然需要决定语义与资源预算,并把这些决定写成可以反复执行的测试。
资料与复现说明
ECMAScript:字符串迭代器,用于核对码点迭代的语义。
ECMAScript:isWellFormed,用于核对孤立代理项检测。
ECMAScript:normalize 与 Unicode UAX #15,用于核对 NFC。
Unicode UAX #29,用于区分码点与字素簇。
Wagner 与 Fischer 原始论文 PDF,用于核对编辑操作模型与经典动态规划背景。
Node.js 命令行文档,用于核对严格拒绝模式的启动参数;本文具体复现运行时为本地验证的 v24.19.0。
正文代码与输出均来自本次实际执行,资料链接于 2026 年 10 月 19 日核验。语言规范页面是持续更新版本,因此具体复现以以上运行时和断言结果为准。图像为独立生成的 AI 概念插画,不用来证明算法步骤。

