Skip to content

Instantly share code, notes, and snippets.

@frostney
Created December 5, 2012 21:11
Show Gist options
  • Save frostney/4219529 to your computer and use it in GitHub Desktop.
Save frostney/4219529 to your computer and use it in GitHub Desktop.
deepEquals in CoffeeScript
deepEquals = (objA, objB) ->
# Simplest of all checks
return true if (objA is objB)
# Both parameters need to be objects
return false if (typeof objA isnt 'object') or (typeof objB isnt 'object')
# Special case for Date objects
if (objA instanceof Date) or (objB instanceof Date)
return false if ((objA instanceof Date) isnt (objB instanceof Date)) or (objA.getTime isnt objB.getTime)
# Get keys of each object and sort them
keysA = Object.keys(objA).sort()
keysB = Object.keys(objB).sort()
# If one of the objects has more keys than the other one, they are obviously not equal
return false if keysA.length isnt keysB.length
# Iterate through first object
for key in keysA
# Quit if key from first object does not exist on the second one
return false unless objB[key]?
# If value is an object, recursively go through all of it again, else directly compare the values
if typeof objA[key] is 'object'
return false if not deepEquals objA[key], objB[key]
else
return false if objA[key] isnt objB[key]
true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment