Jump to content

Recommended Posts

Posted (edited)

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!

Edited by guinness

UDF List:

  Reveal hidden contents

Updated: 22/04/2018

  • 1 month later...
Posted

Updated is module

UDF List:

  Reveal hidden contents

Updated: 22/04/2018

  • 3 months later...
Posted

Updated is module to adhere to the Airbnb style guide

UDF List:

  Reveal hidden contents

Updated: 22/04/2018

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...