Created
August 7, 2017 02:43
-
-
Save ortense/c33ac7cf50f0b4eef0312f3079ef4829 to your computer and use it in GitHub Desktop.
Simple factory function of immutable stack
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
const stack = (...values) => | |
Object.create({ | |
get: index => values[index], | |
add: value => stack(...[value].concat(values)), | |
remove: () => stack(...values.slice(1)), | |
toString: () => `stack [${values.join(' ')}]`, | |
toArray: () => values.slice(0), | |
get length() { return values.length }, | |
constructor: stack | |
}) | |
/* | |
const myStack = stack('a', 'b', 'c') | |
console.log(`${myStack}`) // stack [a b c] | |
console.log(myStack.get(0)) // a | |
console.log(myStack.length) // 3 | |
console.log(myStack.add('x').toString()) // stack [x a b c] | |
console.log(myStack.remove().toString()) // stack [b c] | |
console.log(myStack.toString()) // stack [a b c] | |
console.log(myStack.toArray()) // [ 'a', 'b', 'c' ] | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment