Last active
October 11, 2021 22:50
-
-
Save zazaulola/8006177ec74909893835a4980761d6d9 to your computer and use it in GitHub Desktop.
Queue, thread, stack, task, job, flow, stream
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
const Queue = () => { | |
let idle = true; | |
const stack = [], | |
fx = (...job) => { | |
stack.push(...job); | |
if(idle) | |
(async () => { | |
idle = false; | |
while(stack.length) | |
await stack.shift()(); | |
idle = true; | |
})(); | |
}; | |
Object.defineProperty(fx,'pending',{get: ()=>stack.length}); | |
return fx; | |
}; | |
// ======= Test ========== | |
const wait = ms => new Promise(res => setTimeout(res,ms)); | |
const Job = id => async ()=>{ | |
console.log('Job started: ' + id); | |
await wait(1000); | |
console.log('Job finished: ' + id); | |
}; | |
const queue = Queue(); | |
queue(Job(1)); | |
queue(Job(2)); | |
queue(Job(3),Job(4),Job(5)); | |
queue(Job(6)); | |
queue(Job(7),Job(8)); | |
console.log(queue.pending); | |
setTimeout(()=>console.log(queue.pending),2500); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment