我正在尝试实现一个票务队列系统,默认情况下,它将有3个不同的队列给持票者,分别为严重度1、严重度2和严重度3。其中有一个方法getTicketAtHighestSeverity
,它在最高严重度队列中返回最老的票证,因此它从第一个队列开始,查找队列中的第一个项,如果当前队列为空,则移动到下一个队列,另一个方法getTicketBySeverity
迭代所有所有队列,返回以最高严重度开始的票证。
这是我的实现。
class ticketQueues {
constructor(numOfQueues = 3) {
this.queues = Array.from({length: numOfQueues}).fill([])
}
addSev1(ticket) {
this.queues[0].push(ticket)
}
addSev2(ticket) {
this.queues[1].push(ticket)
}
addSev3(ticket) {
this.queues[2].push(ticket)
}
*getTicketBySeverity() {
for(const queue of this.queues) {
for(const ticket of queue) {
yield ticket
}
}
return null
}
getTicketAtHighestSeverity() {
for(const queue of this.queues) {
for(const ticket of queue) {
return ticket
}
}
return null
}
}
然而,似乎getTicketBySeverity
没有正常工作。
const queues = new ticketQueues()
queues.addSev1({timestamp: Date(), name: 't1'})
queues.addSev2({timestamp: Date(), name: 't2'})
queues.addSev3({timestamp: Date(), name: 't3'})
for(let i = 2; i >= 0; i--) {
console.log(queues.getTicketBySeverity().next().value) // this keeps returning the first item from the queue
}
因为它没有移动到下一个票证,因为它只返回第一个票证。我之所以选择生成器来实现这个方法,是因为我想利用懒惰的评估模型,因为数据集可能很大,我不需要一次就得到所有的票。
有人能用getTicketBySeverity
修复我的实现吗?对这里的命名有什么建议吗?我觉得这里的命名方式,即getTicketBySeverity
和getTicketAtHighestSeverity
可能不是最好的选择。此外,如果您认为这可能不是一个合法的用例,请在这里评论我对生成器的使用情况。
发布于 2021-01-16 21:49:06
一个问题是
this.queues = Array.from({length: numOfQueues}).fill([])
.fill
不能很好地处理非原语(通常),因为新数组中的每个项都是对同一个对象的引用。您只创建了一个数组。问题在于,为什么以下内容不能像人们所期望的那样起作用:
const subarr = [];
arr.push(subarr);
arr.push(subarr);
因为只有一个subarr
。
使用带Array.from
的映射函数显式地为每次迭代创建一个新数组:
this.queues = Array.from({length: numOfQueues}, () => []);
另外,要在迭代器上迭代,可以使用for..of
--或者在找到时从数组中删除找到的项(否则,每次调用它时,它都会返回相同的项)。
您可以通过向生成器传递一个参数并跟踪生成的元素数来控制要立即使用for..of
删除的票数:
class ticketQueues {
constructor(numOfQueues = 3) {
this.queues = Array.from({length: numOfQueues}, () => []);
}
addSev1(ticket) {
this.queues[0].push(ticket)
}
addSev2(ticket) {
this.queues[1].push(ticket)
}
addSev3(ticket) {
this.queues[2].push(ticket)
}
*getTicketsBySeverity(limit) {
let count = 0;
for(const queue of this.queues) {
while (queue.length) {
yield queue.shift();
count++;
if (count === limit) {
return null;
}
}
}
return null
}
}
const queues = new ticketQueues()
queues.addSev1({timestamp: Date(), name: 't1'})
queues.addSev1({timestamp: Date(), name: 't1-2'})
queues.addSev2({timestamp: Date(), name: 't2'})
queues.addSev3({timestamp: Date(), name: 't3'})
for (const ticket of queues.getTicketsBySeverity(3)) {
console.log(ticket);
}
console.log(queues.queues);
https://stackoverflow.com/questions/65755011
复制相似问题