ortense
8/7/2017 - 2:43 AM

Simple factory function of immutable stack

Simple factory function of immutable stack

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' ]
*/