Compare two numeric arrays in CoffeeScript
I was surprised that JavaScript convert all array elements to string before comparing them. This gives unexpected result in some cases.
coffee> [1,3] > [1,2]
true
coffee> [1,10] > [1,2]
false # '10' < '2'
With the following addition to Array prototype:
Array::greaterThan = (otherArray) ->
for element, index in @ when element isnt otherArray[index]
return element > otherArray[index]
false # @ == otherArray
Now it behaves like what I had expected.
coffee> [1,10].greaterThan [1,2]
true
Written by Weera Wu
Related protips
1 Response
Nice, simple solution that can be easily adapted for lessThan and equals. Depending on your use case, you may want to add a check for array length, as
coffee> [0, 9].greaterThan [0, 8, 1]
true
Assuming you wanted to consider longer arrays to be greater, the following modification should work.
Array::greaterThan = (otherArray) ->
thisLen = this.length
otherLen = otherArray.length
if thisLen isnt otherLen
return thisLen > otherLen
for element, index in @ when element isnt otherArray[index]
return element > otherArray[index]
false
over 1 year ago
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Coffeescript
Authors
iam4x
94.17K
ericdfields
63.02K
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#