上次编辑到这里,代码来自缓存 点击恢复默认模板
/**
* @param {Function} queryMultiple
* @param {number} t
* @return {void}
*/
var QueryBatcher = function(queryMultiple, t) {
};
/**
* @param {string} key
* @return {Promise<string>}
*/
QueryBatcher.prototype.getValue = async function(key) {
};
/**
* async function queryMultiple(keys) {
* return keys.map(key => key + '!');
* }
*
* const batcher = new QueryBatcher(queryMultiple, 100);
* batcher.getValue('a').then(console.log); // resolves "a!" at t=0ms
* batcher.getValue('b').then(console.log); // resolves "b!" at t=100ms
* batcher.getValue('c').then(console.log); // resolves "c!" at t=100ms
*/
javascript 解法, 执行用时: 68 ms, 内存消耗: 41.4 MB, 提交时间: 2023-10-15 14:41:23
/**
* @param {Function} queryMultiple
* @param {number} t
*/
var QueryBatcher = function(queryMultiple, t) {
this.fn = queryMultiple
this.cooldown = t
this.batch = []
this.cooling = false
};
QueryBatcher.prototype.queryBatched = async function() {
const batch = this.batch
this.batch = []
const keys = batch.map(v => v[1])
const results = await this.fn(keys)
for (const [i, res] of results.entries()) {
batch[i][0](res)
}
}
QueryBatcher.prototype.consume = async function() {
if (this.batch.length === 0) return
if (this.cooling) return
this.queryBatched()
this.cooling = true
setTimeout(() => {
this.cooling = false
this.consume()
}, this.cooldown)
}
/**
* @param {string} key
* @returns Promise<string>
*/
QueryBatcher.prototype.getValue = async function(key) {
return new Promise((resolve, reject) => {
this.batch.push([resolve, key])
this.consume()
})
};
/**
* async function queryMultiple(keys) {
* return keys.map(key => key + '!');
* }
*
* const batcher = new QueryBatcher(queryMultiple, 100);
* batcher.getValue('a').then(console.log); // resolves "a!" at t=0ms
* batcher.getValue('b').then(console.log); // resolves "b!" at t=100ms
* batcher.getValue('c').then(console.log); // resolves "c!" at t=100ms
*/