-
-
Save hwmrocker/4944245 to your computer and use it in GitHub Desktop.
coffescript deep compare
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
# 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