art-standard-lib
Version:
The Standard Library for JavaScript that aught to be.
135 lines (108 loc) • 2.89 kB
text/coffeescript
###
TODO: This is almost identical to ES6's Map: Switch to using a Polyfill like:
https://github.com/paulmillr/es6-shim
Map is a Key-Value map which preserves order.
Unlike Javascript objects, you can use any object or value as keys. This includes:
Strings
Numbers
null
undefined
Arrays
Objects
Arrays and Objects are assigned a unique id using the StandardLib.Unique library.
"0", "", null, undefined and 0 are all different unique keys and can each have unique values.
###
Unique = require './Unique'
MinimalBaseObject = require './MinimalBaseObject'
{isFunction} = require './Core'
class Node
constructor: (key, value, prev, next) ->
= key
= value
= prev || null
= next || null
prev.next = @ if prev
next.prev = @ if next
remove: ->
n =
p =
if p
p.next = n
= null
if n
n.prev = p
= null
class KeysIterator
constructor: () ->
= false
next: ->
= if
?.next
else
= true
done: !
value: ?.key
class ValuesIterator
constructor: () ->
= false
next: ->
= if
?.next
else
= true
done: !
value: ?.value
# ES6-compatible Map
# DEPRICATED - really, we should just use a standard polyfill
# this class exists because javascript hash keys must be strings
# this simple and inefficient class allows us to use objects as keys
module.exports = if isFunction(global.Map) && (m = new global.Map).set(1, 2) == m then global.Map else
class Map extends MinimalBaseObject
constructor: ->
= 0
= {}
= = null
size: ->
_getNodes: ->
result = []
n =
while n
result.push n
n = n.next
result
keys: -> new KeysIterator
values: -> new ValuesIterator
get: (key) ->
node = [Unique.id key]
node && node.value
set: (key, value) ->
id = Unique.id key
if [id]
[id].value = value
else
++
= [id] = new Node key, value,
= unless
@
# returns the removed element node or undefined
_remove: (key) ->
id = Unique.id key
if n = [id]
--
delete [id]
= n.next if == n
= n.prev if == n
n.remove()
n
else
undefined
# returns true if an element was removed
delete: (key) ->
!! key
forEach: (f) ->
f node.value, node.key, @ for node in ()
undefined
has: (key) -> !![Unique.id key]