Skip to content

Instantly share code, notes, and snippets.

@WebReflection
Last active February 15, 2016 16:12
Show Gist options
  • Save WebReflection/6323064 to your computer and use it in GitHub Desktop.
Save WebReflection/6323064 to your computer and use it in GitHub Desktop.
An incrementally improved approach to a common JavaScript function/utility widely adopted all over. Returns the lowercase type or [[Class]] of a generic variable.
var typeOf = (function(Object, RegExp){
// WTFPL License - http://en.wikipedia.org/wiki/WTFPL
// thanks to @jdalton and @ljharb
var toString = Object.prototype.toString,
cache = (Object.create || Object)(null);
return function typeOf(Unknown) {
var asString = typeof Unknown;
return asString == 'object' ? (
Unknown === null ? 'null' : (
cache[asString = toString.call(Unknown)] || (
cache[asString] = asString
.slice(asString.indexOf(' ') + 1, -1)
.toLowerCase()
)
)
) : asString;
};
}(Object, RegExp));
@mathiasbynens
Copy link

FWIW, RegExp.lastMatch has been in http://javascript.spec.whatwg.org/#regexp.lastmatch as a TODO item since its inception. Still needs to be specced, though.

@WebReflection
Copy link
Author

What's Special About This Code

  • it does not require pre memory allocation as a statically pre-filled map/object would do
  • it is incrementally optimized and compatible with every new native type that will be passed to the function (int32array, htmlcanvaselement, any other available type)
  • it is compatible with every JS environment being string representation agnostic and filled on demand using those representations ([array Array] or [JavaPackage nu.validator] cases )
  • it has ~zero runtime impact avoiding dynamic pre-filling of any native type

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment