示例工程 18-streaming-ui
18-streaming-ui/demo-01-raf-batcher/batcher.ts
type Batcher = {
push(token: string): void;
flush(): void;
pending(): number;
commits(): number;
};
function createBatcher(onFlush: (text: string) => void): Batcher {
let buffer = "";
let commits = 0;
return {
push(token) {
buffer += token;
},
flush() {
if (!buffer) return;
const next = buffer;
buffer = "";
commits += 1;
onFlush(next);
},
pending: () => buffer.length,
commits: () => commits,
};
}
const naive: string[] = [];
const batches: string[] = [];
const batcher = createBatcher((text) => batches.push(text));
for (let index = 1; index <= 60; index += 1) {
const token = `${index} `;
naive.push(token);
batcher.push(token);
if (index % 3 === 0) batcher.flush();
}
batcher.flush();
const naiveCommits = naive.length;
const batchedCommits = batcher.commits();
const same = naive.join("") === batches.join("");
console.log(
JSON.stringify({
evt: "smoke",
ok: naiveCommits === 60 && batchedCommits === 20 && same,
naiveCommits,
batchedCommits,
same,
}),
);