Created
July 5, 2015 16:37
-
-
Save ddlsmurf/3490e61ff090c36ec4ea to your computer and use it in GitHub Desktop.
Better typeof
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::toString | |
hasOwnProperty = Object::hasOwnProperty | |
propertyIsEnumerable = Object::propertyIsEnumerable | |
### @return `undefined|null|boolean|string|symbol|number|NaN|array|arguments|date|object|function` ### | |
(val) -> | |
switch type = typeof val | |
when 'undefined', 'string', 'boolean', 'symbol' | |
return type | |
when 'number' | |
return (if Number.isNaN(val) || (val in [Number.POSITIVE_INFINITY, Number.NEGATIVE_INFINITY]) then 'NaN' else type) | |
when 'object', 'function' | |
return if val == null | |
'null' | |
else if type == "object" && hasOwnProperty.call(val, 'length') && typeof val.length == 'number' && val.length > -1 && val.length % 1 == 0 | |
# beware of https://bugs.webkit.org/show_bug.cgi?id=142792 | |
if hasOwnProperty.call(val, 'callee') && !propertyIsEnumerable.call(val, 'callee') | |
'arguments' | |
else | |
'array' | |
else | |
if toString.call(val) == '[object Date]' | |
'date' | |
else | |
type | |
break # fo' linting (linter cant see that all above paths return) | |
else | |
throw Error("Unknown object kind: #{val}") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment