Skip to content

Instantly share code, notes, and snippets.

@hugoferreira
Last active April 2, 2019 01:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hugoferreira/91429f413761f62ec4020a3fe9744aeb to your computer and use it in GitHub Desktop.
Save hugoferreira/91429f413761f62ec4020a3fe9744aeb to your computer and use it in GitHub Desktop.
Tests the behaviour of an AsyncQueue by doing a random permutation of Enqueues and Dequeues
const isArraySorted = require('is-array-sorted')
async function testAsyncQueueBehavior(nOps: number): Promise<Boolean> {
const result = new Array<number>()
const q = new AsyncQueue<number>()
const enqueue = (m: number) => q.enqueue(m)
const dequeue = () => q.dequeue()
const promises = Array<Promise<void>>()
let enqueues = 0
let dequeues = 0
// Do a random permutation of enqueing and dequeing
for (let i = 0; i < nOps; i += 1) {
if (Math.random() > 0.5) {
enqueues += 1
// console.log(`${Date.now()} Enqueuing ${enqueues}`)
enqueue(enqueues)
} else {
dequeues += 1
// console.log(`${Date.now()} Dequeuing`)
promises.push(dequeue().then(v => { result.push(v) }))
}
}
// console.log(`Total enqueues ${enqueues}; dequeues ${dequeues}`)
const pending = Math.min(enqueues, dequeues)
await Promise.all(promises.slice(0, pending))
// Length should be equal minimum between enqueues and dequeues
const isLengthOk = pending === result.length
// Messages should be ordered
const isSorted = isArraySorted(result)
return isLengthOk && isSorted
}
setInterval(() => { }, 1000); // run program forever until an explicit exit occurs
(async () => {
const success = await testAsyncQueueBehavior(100)
console.log(success)
process.exit()
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment