Looking at the following from CoffeeScript Ristretto:
QueueMaker = ->
do (queue = undefined) ->
array: []
head: 0
tail: -1
pushTail: (value) ->
queue.array[tail += 1] = value
pullHead: ->
unless queue.isEmpty()
do (value = queue.array[queue.head]) ->
queue.array[queue.head] = undefined
queue.head += 1
value
isEmpty: ->
queue.tail < queue.head
It's possible to mutate queue.head - http://jsfiddle.net/VQLNG/.
queue = QueueMaker()
queue.head = 666
console.log queue
How can I write the above function so that head isn't public?
JavaScript doesn't have private properties so CoffeeScript doesn't have them either.
However, you can simulate private properties in many cases by using function scopes to hide things and closures to access the hidden things.
A simple stack implementation should demonstrate the technique:
stackis a local variable in theStackfunction so it cannot be accessed or seen from outsideStack. Thepushandpopfunctions simply proxy to thestackarray and thetoArrayfunction is the only way to see whatstacklooks like. Only those three functions have access tostackso it is effectively private and each time you callStack, you get a new localstack.Demo: http://jsfiddle.net/ambiguous/C8V5R/
Adapting your queue to use this technique to hide
array,headandtailis left as an exercise.