提问人:Ella 提问时间:8/27/2023 更新时间:8/27/2023 访问量:34
lodash groupBy 是一个长时间的同步操作,使所有其他异步操作都匮乏
lodash groupBy is a long sync operation starving all other async operations
问:
我正在一个大数组上使用 lodash group by, 该操作需要几分钟时间,这会使所有其他异步承诺者匮乏 (因为我们没有发布上下文)
有没有人建议使用不同的库\修改我对groupBy的使用来解决这个问题?
答:
1赞
Dimava
8/27/2023
#1
Sonce groupBy 只是
function groupBy<T, V extends PropertyKey>(
list: T[], get: (v:T) => V,
): Record<V, T[]> {
const r = {} as Record<V, T[]>
for (const el of list) {
(r[get(el)] ??= []).push(el)
}
return r
}
如果时间过长,您可以轻松添加拦截器以等待:
async function groupBy<T, V extends PropertyKey>(
list: T[], get: (v:T) => V,
): Record<V, T[]> {
const r = {} as Record<V, T[]>
let now = performance.now()
for (const el of list) {
// if `get` is fast, better to smth like `if (i%100==0)` here
if (performance.now() - now > 10 /*ms*/) {
// break the execution
await new Promise(setTimeout) // or whatever waiting function
now = performance.now()
}
(r[get(el)] ??= []).push(el)
}
return r
}
评论