Created
June 26, 2016 08:56
-
-
Save stringparser/c957ab0e2b91b5f5cb461f7aecadefbb to your computer and use it in GitHub Desktop.
smaller lodash.isEqual
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
__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