Last active
December 30, 2015 22:49
-
-
Save harmstyler/7896595 to your computer and use it in GitHub Desktop.
Compares two arrays and returns boolean value. Coffeescript and Javascript versions provided
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
Array::equals = (array) -> | |
return false unless array | |
return false unless @length is array.length | |
i = 0 | |
while i < @length | |
if this[i] instanceof Array and array[i] instanceof Array | |
# Check and recurse into the nested arrays | |
return false unless this[i].equals(array[i]) | |
else if this[i] instanceof Object and array[i] instanceof Object | |
# Stringify objects for comparison | |
return false unless JSON.stringify(this[i]) is JSON.stringify(array[i]) | |
else return false unless this[i] is array[i] | |
i++ | |
true |
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
Array.prototype.equals = function(array) { | |
var i; | |
if (!array) { | |
return false; | |
} | |
if (this.length !== array.length) { | |
return false; | |
} | |
i = 0; | |
while (i < this.length) { | |
if (this[i] instanceof Array && array[i] instanceof Array) { | |
if (!this[i].compare(equals[i])) { | |
return false; | |
} | |
} else if (this[i] instanceof Object && array[i] instanceof Object) { | |
if (JSON.stringify(this[i]) !== JSON.stringify(array[i])) { | |
return false; | |
} | |
} else { | |
if (this[i] !== array[i]) { | |
return false; | |
} | |
} | |
i++; | |
} | |
return true; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment