Files
Neo-ZQYY/apps/miniprogram - 副本/miniprogram/utils/chat.ts

50 lines
1.2 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* 对话工具函数
* simulateStreamOutput 为异步函数(使用 setTimeout
* simulateStreamOutputSync 为同步纯函数(用于测试)
*/
/**
* 模拟流式输出:逐字追加调用 callback
* @param text 完整文本
* @param callback 每次追加后的回调,参数为当前已输出的子串
* @returns Promise输出完成后 resolve
*/
export function simulateStreamOutput(
text: string,
callback: (partial: string) => void
): Promise<void> {
return new Promise((resolve) => {
if (text.length === 0) {
callback('')
resolve()
return
}
let index = 0
const tick = () => {
index++
callback(text.slice(0, index))
if (index < text.length) {
setTimeout(tick, 50)
} else {
resolve()
}
}
setTimeout(tick, 50)
})
}
/**
* 同步版流式输出:返回逐字追加的子串数组(用于测试)
* @param text 完整文本
* @returns 逐步增长的子串数组,如 "abc" → ["a", "ab", "abc"]
*/
export function simulateStreamOutputSync(text: string): string[] {
const result: string[] = []
for (let i = 1; i <= text.length; i++) {
result.push(text.slice(0, i))
}
return result
}