Last active
September 19, 2019 12:48
-
-
Save joduplessis/6abf1dfd79ac0d83e79bb2de3fed17bb to your computer and use it in GitHub Desktop.
Exploring synchronous queues in JS - base for one of projects I'm working on (contain lib & implementation). See https://github.com/joduplessis/keg
This file contains 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 Keg { | |
static instance; | |
taps = {}; | |
queue = {}; | |
constructor() { | |
setInterval(() => { | |
//console.log(this.taps) | |
//console.log(this.queue) | |
}, 1000) | |
} | |
static tap(tapName, callback) { | |
if (!this.instance) this.instance = new Keg() | |
// If this outlet doesn't exist - create it | |
if (!this.instance.taps[tapName]) this.instance.taps[tapName] = [] | |
// Push our callback to the stack | |
this.instance.taps[tapName].push(callback) | |
// Run it as soon as | |
this.instance.next(tapName) | |
} | |
next(tapName) { | |
// Value to push out | |
const value = this.queue[tapName][0] | |
// Remove it from the stack | |
this.queue[tapName].shift() | |
// If it's empty, do nothing | |
if (!value) return | |
// Send it out to all taps | |
this.taps[tapName].map(tap => tap(value, () => { | |
this.next(tapName) | |
})) | |
} | |
static refill(tapName, value) { | |
// If there isn't an object, create it | |
if (!this.instance) this.instance = new Keg() | |
// If this tap doesn't exist, create it | |
if (!this.instance.queue[tapName]) this.instance.queue[tapName] = [] | |
// Add this value to the Q | |
this.instance.queue[tapName].push(value) | |
// If there is 1 callback ready - start mapping it | |
if (this.instance.taps[tapName]) this.instance.next(tapName) | |
} | |
} | |
Keg.refill('demo', "Send #1") | |
Keg.refill('demo', "Send #2") | |
Keg.refill('demo', "Send #3") | |
Keg.tap('demo', (val, next) => { | |
console.log("Received: ", val) | |
next() | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment