如何解决JavaScript Generator:实现票务队列系统
我正在尝试实现一个票证队列系统,默认情况下,它将有 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
}
因为它不会移动到下一张票,因为它只返回第一张票。我选择 Generator 来实现这个方法的原因是我想利用惰性评估模型,因为数据集可能很大,我不想一次获得所有的票。
有人可以使用 getTicketBySeverity
修复我的实现吗?对这里的命名有什么建议吗?我觉得这里的命名,即 getTicketBySeverity
和 getTicketAtHighestSeverity
可能不是最好的选择。此外,如果您认为这可能不是一个合法的用例,请随时在此处评论我对 Generator 的使用。
解决方法
一个问题是
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);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。