Last active
August 29, 2015 14:10
-
-
Save jabney/438dab501101e60b0fbe to your computer and use it in GitHub Desktop.
Encode an object's type as a numeric value.
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
// 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