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:
stack
is a local variable in theStack
function so it cannot be accessed or seen from outsideStack
. Thepush
andpop
functions simply proxy to thestack
array and thetoArray
function is the only way to see whatstack
looks like. Only those three functions have access tostack
so 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
,head
andtail
is left as an exercise.