Skip to content

Instantly share code, notes, and snippets.

@hwmrocker
Forked from ruxkor/cmp.coffee
Last active December 13, 2015 16:59
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 hwmrocker/4944245 to your computer and use it in GitHub Desktop.
Save hwmrocker/4944245 to your computer and use it in GitHub Desktop.
coffescript deep compare
# comparison function, checking also the contents of elements if we are comparing 2 arrays.
# very useful for sorting.
cmp = (a,b) ->
typemap =
'null': 0
'undefined': 0
'number': 1
'string': 1
'object': 2
if typemap[typeof a] > typemap[typeof b]
return 1
else if typemap[typeof a] < typemap[typeof b]
return -1
if (typeof a) == 'object' and a.constructor == Array
elemCmp = 0
[0...Math.min(a.length,b.length)].some (i) ->
elemCmp = cmp(a[i],b[i])
elemCmp != 0
return elemCmp
if a > b
return 1
else if a < b
return -1
return 0
one = [2,10]
two = [2,5,10]
three = [2,5,5]
all = [one, two, three]
all.sort(cmp)
console.info all
# returns [ three, two, one ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment