示例工程 61-chat-ui-streaming
61-chat-ui-streaming/demo-01-stream-batching/batch.ts
type Chunk = { at: number; text: string };
const CHUNKS: Chunk[] = [
{ at: 0, text: "我会" },
{ at: 8, text: "先更新" },
{ at: 16, text: "配置," },
{ at: 24, text: "再说明" },
{ at: 32, text: "改动。" },
];
function batched(chunks: Chunk[], windowMs: number): string[] {
const frames: string[] = [];
let pending = "";
let openedAt: number | null = null;
for (const chunk of chunks) {
if (openedAt === null) openedAt = chunk.at;
pending += chunk.text;
if (chunk.at - openedAt >= windowMs) {
frames.push(pending);
pending = "";
openedAt = null;
}
}
if (pending) frames.push(pending);
return frames;
}
function immediate(chunks: Chunk[]): string[] {
return chunks.map((chunk) => chunk.text);
}
const frames = batched(CHUNKS, 16);
const naive = immediate(CHUNKS);
const full = CHUNKS.map((chunk) => chunk.text).join("");
const ok =
naive.length === 5 &&
frames.length === 2 &&
frames.join("") === full &&
frames.every((frame) => frame.length > 0);
console.log(
JSON.stringify({
evt: "smoke",
ok,
chunks: CHUNKS.length,
naiveRenders: naive.length,
batchedRenders: frames.length,
frames,
full,
}),
);
export {};