Search the Community
Showing results for tags 'is type'.
-
Extend an object e.g. window with the likes of isDate or isNumber. /** * is* module * Idea by JavaScript Weblog, URL: https://javascriptweblog.wordpress.com/2011/08/08/fixing-the-javascript-typeof-operator/ * * @param {object} global Object to extend with the following isType functions * @return {undefined} */ (function isTypeModule(Object, global) { // Constants // Fields var _nativeObjectToString = Object.prototype.toString; // Parsing the native toString() return value e.g. [object Object] var _reTypeOf = /(?:^\[object\s(.*?)\]$)/; [ 'Arguments', 'Array', 'Boolean', 'Date', 'Error', 'Float32Array', 'Float64Array', 'Function', 'GeneratorFunction', 'Int32Array', 'Int8Array', 'Map', 'Null', 'Number', 'Object', 'Promise', 'RegExp', 'Set', 'String', 'Symbol', 'Uint16Array', 'Uint32Array', 'Uint8Array', 'Uint8ClampedArray', 'Undefined', 'WeakMap', 'WeakSet', ].forEach(function forEachTypeName(typeName) { var typeNameMatch = typeName.toLowerCase(); var isTypeFn = 'is' + typeName; // Extend if a function doesn't exist on the public API already global[isTypeFn] = global[isTypeFn] || function isTypeNameMatch(value) { return _nativeObjectToString.call(value) .replace(_reTypeOf, '$1') .toLowerCase() === typeNameMatch; }; }); }(window.Object, window)); // Change the second window argument to the object you wish to extend with the following is* functions // Example (function example(window) { // Example of using the is* functions from above window.console.log('isNumber: ', window.isNumber(100)); window.console.log('isDate: ', window.isDate(null)); window.console.log('isDate: ', window.isDate(new Date())); }(window)); The list of available is* functions can be found in the typeNames array e.g. isArguments() or isNull(). Enjoy!