Created
February 26, 2013 08:47
-
-
Save the-teacher/5037053 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@compactArray = (array) -> | |
array.filter (e) -> return e | |
class @OrderedHash | |
constructor: (array = []) -> | |
@data = [] | |
@data = array if array.length > 0 | |
get: -> @data | |
push: (obj) -> | |
@data.push obj | |
@sortByKey() | |
deleteByKey: (key) -> | |
for index, item of @data | |
for name, value of item | |
if name.toString() is key.toString() | |
delete @data[index] | |
@data = compactArray @data | |
first: -> @data[0] | |
last: -> @data[@data.length - 1] | |
sortByKey: (reverse = false) -> | |
@data.sort (a, b) -> | |
akey = key for key, value of a | |
bkey = key for key, value of b | |
# numeric keys | |
anum = parseInt akey, 10 | |
bnum = parseInt bkey, 10 | |
if typeof(anum) is 'number' and typeof(bnum) is 'number' | |
akey = anum | |
bkey = bnum | |
# to reverse? | |
[akey, bkey] = [bkey, akey] if reverse | |
r = if akey > bkey | |
1 | |
else if akey < bkey | |
-1 | |
else | |
0 | |
sortByValue: (reverse = false) -> | |
@data.sort (a, b) -> | |
avalue = value.toString().toLowerCase() for key, value of a | |
bvalue = value.toString().toLowerCase() for key, value of b | |
[avalue, bvalue] = [bvalue, avalue] if reverse | |
r = if avalue > bvalue | |
1 | |
else if avalue < bvalue | |
-1 | |
else | |
0 | |
toValArray: -> | |
_a = [] | |
for index, item of @data | |
for key, val of item | |
_a.push val | |
_a | |
toKeyArray: -> | |
_a = [] | |
for index, item of @data | |
for key, val of item | |
_a.push key | |
_a |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment