Skip to content

Instantly share code, notes, and snippets.

@boatilus
Last active December 25, 2015 17:49
Show Gist options
  • Save boatilus/7016354 to your computer and use it in GitHub Desktop.
Save boatilus/7016354 to your computer and use it in GitHub Desktop.
Dynamically-resizing vector implementation around JavaScript typed arrays
define [], ->
return class Vector
constructor: (@type, @wordLength, initialSize) ->
@buffer = new ArrayBuffer ((initialSize or 10) * wordLength) / 8
@view = new window[type + wordLength + 'Array'] @buffer
type: ''
buffer: null
view: null
length: 0
wordLength: 0
at: (index) -> return @view[index]
front: -> return @view[0]
back: -> return @view[@length]
set: (index, value) -> @view[index] = value; return this
size: -> return @length
empty: -> return @length is 0
capacity: -> return @view.length
data: -> return @view
reserve: (size) ->
@reAlloc size
return this
pushBack: (value) ->
if @length < @view.length
@view[@length] = value
else
@reAlloc @view.length * 2
@view[@length] = value
++@length
return this
reAlloc: (size) ->
newLength = 0
# Confirm need to re-allocate; return if not
if size > @view.length then newLength = (size * @wordLength) / 8 else return
tempBuf = new ArrayBuffer newLength
tempView = new window[@type + @wordLength + 'Array'] tempBuf
i = 0
length = @length
# Copy the values from the member view to the temporary view
while (i < length)
tempView[i] = @view[i]
++i
delete @buffer; delete @view
@buffer = tempBuf
@view = tempView
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment