Skip to content

Instantly share code, notes, and snippets.

@nmccready
Created April 5, 2014 18:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nmccready/9995986 to your computer and use it in GitHub Desktop.
Save nmccready/9995986 to your computer and use it in GitHub Desktop.
class LRUCache
constructor: (size_limit) ->
@limit = size_limit or Infinity
@data = {}
@size = 0
@order = []
set: (key, val) ->
@data[key] = val
@size++
@order.push key
if @size > @limit
@order.splice 0, 1
delete @data[@order[0]]
@size--
get: (key) ->
for item, index in @order
if item is key
@order.splice index, 1
@order.push key
@data[key]
@nmccready
Copy link
Author

note splice is not O(1) t is O(n) , see here http://stackoverflow.com/questions/11514308/big-o-of-javascript-arrays
javascript arrays O -

  • Access - O(1)
  • Appending - Amortized O(1) (sometimes resizing the hashtable is required; usually only insertion is required)
  • Prepending - O(n) via unshift, since it requires reassigning all the indexes
  • Insertion - Amortized O(1) if the value does not exist. O(n) if you want to shift existing values (Eg, using splice).
  • Deletion - Amortized O(1) to remove a value, O(n) if you want to reassign indices via splice.
  • Swapping - O(1)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment