任务
把每条约束展开为上下界,过滤候选版本后升序排列,取最后一个作为最佳版本。
契约
- 输入:JSON 对象:{ constraints: string[], available: string[] }
- 输出:JSON 对象:{ best: string | null, satisfying: string[] }
样例
- 输入
{"constraints":["^1.2.0","<2.0.0"],"available":["1.1.0","1.2.5","1.9.3","2.0.0"]}-> 期望{"best":"1.9.3","satisfying":["1.2.5","1.9.3"]}。caret 把主版本锁在 1,上界因此排除 2.0.0。 - 输入
{"constraints":["~1.4.0"],"available":["1.4.0","1.4.9","1.5.0"]}-> 期望{"best":"1.4.9","satisfying":["1.4.0","1.4.9"]}。tilde 锁住次版本,因此排除了 1.5.0。
参考实现
function solve({ constraints, available }) {
const parse = (v) => String(v).replace(/^v/, '').split('.').map(Number);
const compare = (a, b) => {
const A = parse(a);
const B = parse(b);
for (let i = 0; i < 3; i++) if ((A[i] ?? 0) !== (B[i] ?? 0)) return (A[i] ?? 0) - (B[i] ?? 0);
return 0;
};
const satisfies = (v) =>
constraints.every((raw) => {
const c = String(raw).trim();
if (c.startsWith('^')) return compare(v, c.slice(1)) >= 0 && parse(v)[0] === parse(c.slice(1))[0];
if (c.startsWith('~')) return compare(v, c.slice(1)) >= 0 && parse(v)[1] === parse(c.slice(1))[1];
if (c.startsWith('>=')) return compare(v, c.slice(2)) >= 0;
if (c.startsWith('>')) return compare(v, c.slice(1)) > 0;
if (c.startsWith('<=')) return compare(v, c.slice(2)) <= 0;
if (c.startsWith('<')) return compare(v, c.slice(1)) < 0;
return compare(v, c) === 0;
});
const satisfying = available.filter(satisfies).sort(compare);
return { best: satisfying.length ? satisfying[satisfying.length - 1] : null, satisfying };
}
为什么有效
把 caret 与 tilde 的语义当成“差不多”时,依赖升级就会出错。自动合并工具正是靠显式求解这套语义。
区间约束是合取关系:每个子句都要成立,结果升序排列后再取最后一个。