Created
November 29, 2018 17:01
-
-
Save BigAB/dbe85c00420fdcd2910bc28a927be183 to your computer and use it in GitHub Desktop.
This is a simple queue structure, but it demostrates 2 things, private data in a class, and having both a construtctor and a factory function that do the exact same thing
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
function Queue(){ | |
return createQueue(); | |
} | |
function createQueue() { | |
const queue = []; | |
const q = Object.create(Queue.prototype, { | |
constructor: { | |
configurable: true, | |
enumerable: false, | |
value: Queue, | |
writable: true, | |
} | |
}); | |
const methods = { | |
enqueue(item){ return queue.push(item); }, | |
dequeue() { return queue.shift() }, | |
peek() { return queue[0] }, | |
debug() { return queue } | |
} | |
Object.assign(q, methods); | |
Object.defineProperty(q, 'length', { get(){ return queue.length } }) | |
return Object.create(q); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment