Skip to content

Instantly share code, notes, and snippets.

@ruxkor
Last active June 6, 2017 11:23
Show Gist options
  • Save ruxkor/2772234 to your computer and use it in GitHub Desktop.
Save ruxkor/2772234 to your computer and use it in GitHub Desktop.
sensible comparison function for js
# 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 Array.isArray a
elemCmp = 0
[0...Math.min(a.length,b.length)].some (i) ->
elemCmp = cmp a[i], b[i]
elemCmp != 0
return elemCmp or cmp a.length, b.length
if a > b
return 1
else if a < b
return -1
return 0
one = [2, 10]
two = [2, 5, 10]
three = [2, 5, 5]
four = [2, 10, -1]
l_unsorted = [one, two, three, four]
l_sorted = l_unsorted[..]
l_sorted.sort cmp
console.info l_unsorted, '-->', l_sorted
assert = require 'assert'
assert.deepEqual l_sorted, [three, two, one, four]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment