-
-
Save rwaldron/1212234 to your computer and use it in GitHub Desktop.
Stack implementation using ES6 proxies
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
/* | |
* Another ES6 Proxy experiment. This one creates a stack whose underlying | |
* implementation is an array. The proxy is used to filter out everything | |
* but "push", "pop", and "length" from the interface, making it a pure | |
* stack where you can't manipulate the contents. | |
*/ | |
var Stack = (function(){ | |
var stack = [], | |
allowed = [ "push", "pop", "length" ]; | |
return Proxy.create({ | |
get: function(receiver, name){; | |
if (allowed.indexOf(name) > -1){ | |
if(typeof stack[name] == "function"){ | |
return stack[name].bind(stack); | |
} else { | |
return stack[name]; | |
} | |
} else { | |
return undefined; | |
} | |
} | |
}); | |
}); | |
var mystack = new Stack(); | |
mystack.push("hi"); | |
mystack.push("goodbye"); | |
console.log(mystack.length); //1 | |
console.log(mystack[0]); //undefined | |
console.log(mystack.pop()); //"goodbye" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment