我有一个返回 Iterable 的咖喱批处理函数。如果你用一个同步调用它,Iterable
你会得到一个同步Iterable
,如果你给一个AsyncIterable
你会得到一个AsyncIterable
。但是我这辈子都不能让函数实现接受同步重载。
这个特定的定义是什么给出了错误
export function batch(size: number): <T>(curriedIterable: Iterable<T>) => IterableIterator<T[]>
这是所有代码
async function* _batch<T>(size: number, iterable: AsyncIterable<T>) {
let dataBatch: T[] = []
for await (const data of iterable) {
dataBatch.push(data)
if (dataBatch.length === size) {
yield dataBatch
dataBatch = []
}
}
if (dataBatch.length > 0) {
yield dataBatch
}
}
function* _syncBatch<T>(size: number, iterable: Iterable<T>) {
let dataBatch: T[] = []
for (const data of iterable) {
dataBatch.push(data)
if (dataBatch.length === size) {
yield dataBatch
dataBatch = []
}
}
if (dataBatch.length > 0) {
yield dataBatch
}
}
export function batch(size: number): <T>(curriedIterable: AsyncIterable<T>) => AsyncIterableIterator<T[]>
export function batch<T>(size: number, iterable: AsyncIterable<T>): AsyncIterableIterator<T[]>
export function batch(size: number): <T>(curriedIterable: Iterable<T>) => IterableIterator<T[]>
export function batch<T>(size: number, iterable: Iterable<T>): IterableIterator<T[]>
export function batch<T>(size: number, iterable?: Iterable<T> | AsyncIterable<T>) {
if (iterable === undefined) {
return curriedIterable => batch(size, curriedIterable)
}
if (iterable[Symbol.asyncIterator]) {
return _batch(size, iterable as AsyncIterable<T>)
}
return _syncBatch(size, iterable as Iterable<T>)
}