Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
smaller lodash.isEqual
__toString = Object.prototype.toString
isEqual = (a, b) ->
if arguments.length < 2
return false # cannot compare
typeA = typeOf(a)
typeB = typeOf(b)
# falsy values can be compared by reference except for NaN
# NOTE: window.isNaN fails for isNaN("NaN"), Number.isNaN is not supported in IE11
# source: http://kangax.github.io/compat-table/es6/#test-Number.isNaN
if !a or !b
return a == b or (typeA == 'number' and isNaN(a) and isNaN(b))
# truthy primitives can be compared by reference
if isPrimitive(a) or isPrimitive(b)
return a == b
# regexps are other kind of... thing (no keys, no way to compare on the loop below)
if typeA == 'regexp' or typeB == 'regexp'
return a.toString?() == b.toString?()
# "a" and "b" are objects (compare recursively)
for keyA, valueA of a
if !isEqual(b[keyA], valueA)
return false
return true
typeOf = (value) ->
return __toString.call(value).match(/(\w+)\]/).pop();
isPrimitive = (value) ->
return false if arguments.length < 1
return /undefined|null|string|number|boolean|symbol/i.test(
typeOf(value)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment