Skip to content

Instantly share code, notes, and snippets.

@JLChnToZ
Last active August 29, 2015 14:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JLChnToZ/7c33f8a4ec2c8c05e9a8 to your computer and use it in GitHub Desktop.
Save JLChnToZ/7c33f8a4ec2c8c05e9a8 to your computer and use it in GitHub Desktop.
Deep compare 2 JavaScript objects
compare = (->
compareByType =
"array": (a, b) ->
return false if a.length isnt b.length
return false for i in [0...a.length] when not equals a[i], b[i]
true
"object": (a, b) ->
return false for i of a when not (b.hasOwnProperty i) or not equals a[i], b[i]
return false for i of b when not a.hasOwnProperty i
true
"date": (a, b) ->
a.getTime() is b.getTime()
"regexp": (a, b) ->
a.toString() is b.toString()
"function": (a, b) ->
compareByType["regexp"] a, b
getType = (val) ->
return "undefined" if val is undefined
return "null" if val is null
type = typeof val
switch type
when "object"
type = (Object::toString.call val).match(/^\[object\s(.*)\]$/)[1].toLowerCase()
when "number"
type = if (val.toString().indexOf ".") > 0 then "float" else "integer"
type
equals = (a, b) ->
return true if a is b
aType = getType a
bType = getType b
return false if aType isnt bType
if compareByType.hasOwnProperty aType then compareByType[aType] a, b else `a == b`
equals
)()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment