Created
July 25, 2022 12:17
-
-
Save m-allanson/7c88da0895ec269f29386098b448b31b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Queue { | |
constructor(private items: number[] = []) {} | |
async count() { | |
return this.items.length; | |
} | |
async pop() { | |
return this.items.shift(); | |
} | |
async push() { | |
const randomInt = Math.floor(Math.random() * (1000 - 1)) | |
return this.items.push(randomInt); | |
} | |
} | |
const wait = function() { | |
return new Promise((resolve) => { | |
setTimeout(() => { | |
console.log('waited'); | |
resolve(undefined); | |
}); | |
}); | |
} | |
class Runner { | |
constructor(private queue: Queue) {} | |
async *asyncItemIterator(queue: Queue) { | |
while (await queue.count() > 0) { | |
await wait(); | |
yield queue.pop(); | |
} | |
} | |
async process() { | |
const processNextItem = this.asyncItemIterator(this.queue); | |
setTimeout(() => {console.log('Log second')}); | |
console.log('Log first') | |
for await (const item of processNextItem) { | |
console.log(`Nonblocking item: ${item}`); | |
} | |
} | |
} | |
const queueItems = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]; | |
const queueInstance = new Queue(queueItems); | |
const runner = new Runner(queueInstance); | |
runner.process(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Run in TS Playground