实现说明
全部逻辑都在函数 allocate中。
循环只出现在 for (const size of sizes),它的每次迭代处理一个元素。
使用要点
- 直接运行文件,输出会带上标签,比如
packed hex:、fits 64 bits:——输出的每一行都能指回产生它的那次调用。
常见问题
安装包是准备工作的一部分吗?
不需要。只用内建 API,安装这一步可以省掉。 文件在加载时定义 allocate。
主要签名是 function allocate(bytes: number, block: BlockSize)
核心语句
return blocks * Number(block);
代码示例
// Bigint literal types restrict allocation sizes to declared values.
type BlockSize = 8n | 16n | 32n;
function allocate(bytes: number, block: BlockSize): number {
const blocks = Math.ceil(bytes / Number(block));
return blocks * Number(block);
}
const sizes: BlockSize[] = [8n, 16n, 32n];
for (const size of sizes) {
console.log(size + "n ->", allocate(100, size));
}
// @ts-expect-error only the declared bigint literals are accepted
allocate(100, 24n);
const packed: bigint = 1n << 40n;
console.log("packed hex:", packed.toString(16));
console.log("fits 64 bits:", packed < 1n << 64n);