Skip to content

Instantly share code, notes, and snippets.

@ddlsmurf
Created July 5, 2015 16:37
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 ddlsmurf/3490e61ff090c36ec4ea to your computer and use it in GitHub Desktop.
Save ddlsmurf/3490e61ff090c36ec4ea to your computer and use it in GitHub Desktop.
Better typeof
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