Array LocalStorage básico com funcionalidade de limite, uid e pesquisa

Oi,

Eu fiz esta pequena joia que pode ser implementada rapidamente para armazenar e obter informações sobre o array. Eu precisava armazenar a última quantidade de itens classificados do último clicado até o mais antigo. Eu usei este array para fazer o unshifting, popping, push, purging etc. Funciona melhor para salvar o histórico, pois tem todas as coisas que são necessárias para ele (quantidade limitada, pesquisa para excluir objetos no array)

De qualquer forma, aqui está o coffeescript, a parte pública é o que você deseja usar:

    Array::remove = (from, to) ->
rest
= @slice((to or from) + 1 || @length)
@length = if from < 0 then this.length + from else from
@push.apply @, rest

# Simple class that makes array extend into the localstorage and updates accordingly
class @LocalStorageArray
constructor: ( @strUid = undefined, @numLimit = 0 ) ->
if not @strUid
@strUid = do () ->
numTotal
= 10
numString
= ''
for i in [0...numTotal] by 1 then numString = numString + Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1)
numString



## Private

_fetch
: ->
@arrItems = localStorage.getItem @strUid
@arrItems = if @arrItems then JSON.parse(@arrItems) else []
@arrItems
_update
: ->
localStorage
.setItem @strUid, JSON.stringify(@arrItems)
@_fetch()
_do
: ( fnCallback, arrArguments = [] ) ->
@_fetch()
fnCallback
.bind(@).apply @, arrArguments
@_update()
_checkLimit
: ( boolReverse = false ) ->
if @numLimit
numDifference
= @arrItems.length - @numLimit
if numDifference > 0
if boolReverse
@arrItems = @arrItems.slice 0, @arrItems.length-numDifference
else
@arrItems = @arrItems.slice numDifference


## Public

setKey
: ( @strUid ) ->
getKey
: -> @strUid
get: -> @_fetch()
set: ( @arrItems ) -> @_update()
unshift
: ( anyItem ) ->
@_do (( anyItem ) ->
@arrItems.unshift anyItem
@_checkLimit true
), [anyItem]
push
: ( anyItem ) ->
@_do (( anyItem ) ->
@arrItems.push anyItem
@_checkLimit false
), [anyItem]
pop
: -> @_do -> @arrItems.pop()
purge
: -> @_do -> @arrItems = []
remove: ( numIndex ) -> @_do -> @arrItems.remove numIndex
searchAndDestroy
: ( strProperty, strValue ) ->
objMatched
= @matchProperty(strProperty, strValue)
if objMatched.matched then @remove objMatched.index



matchProperty
: ( strProperty, strValue ) ->
# Tries to match on property in objects in the array for searching for duplicates
@_fetch()
objMatched
=
matched
: false
index
: 0

for objItem in @arrItems by 1
if typeof objItem is 'object'
if objItem[strProperty] is strValue
objMatched
=
matched
: true
index
: _i
break;

objMatched