Skip to content

Instantly share code, notes, and snippets.

@jabney
Last active August 29, 2015 14:10
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 jabney/438dab501101e60b0fbe to your computer and use it in GitHub Desktop.
Save jabney/438dab501101e60b0fbe to your computer and use it in GitHub Desktop.
Encode an object's type as a numeric value.
// encode.js MIT License © 2014 James Abney http://github.com/jabney
// Encode built-in type as a numeric value.
//
// typeOf(null); // => 'Null'
// typeOf(undefined); // => 'Undefined'
// typeOf([]); // => 'Array'
//
// encodeType(null); // => 1
// encodeType(undefined); // => 2
// encodeType(1); // => 3
// encodeType([]); // => 4
//
// Encode an object's type as a number.
encodeType = (function() {
var types = {
'Null': 1,
'Undefined': 2,
'Number': 3,
'Array': 4,
'String': 5,
'Object': 6,
'Boolean': 7,
'Function': 8,
'Symbol': 9,
'Date': 10,
'Error': 11,
'RegExp': 12,
'Arguments': 13,
'Math': 14,
'JSON': 15
};
// Return a type code.
function get(type) {
// Return 0 for undefined types.
return types[type] || 0;
}
// Return a numeric code corresponding to an object's type.
return function encodeType(obj) {
return get(typeOf(obj));
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment