Source: polyfill/Array.js

// Licensed Materials - Property of IBM
//
// IBM Watson Analytics
//
// (C) Copyright IBM Corp. 2015, 2018
//
// US Government Users Restricted Rights - Use, duplication or
// disclosure restricted by GSA ADP Schedule Contract with IBM Corp.

( function( Array, ObjectPolyfill, NMap, NSet )
{
"use strict";

// This module uses bitwise operators to enforce unsigned ints or perform other optimizations.
/*jshint bitwise:false*/

var toObject = ObjectPolyfill.toObject,
    isCallable = ObjectPolyfill.isCallable,
    ensureCallable = ObjectPolyfill.ensureCallable;
// Store reference to Object.prototype.toString for convenience and to (hopefully) grab the original before modification.
var toString = Object.prototype.toString;

/** @lends module:barejs/polyfill.Array */
var stat = {},
/** @lends module:barejs/polyfill.Array# */
    proto = {};


/**
 * Method that performs the actual iteration
 * @memberof module:barejs/polyfill.Array~
 * @private
 */
function iterate( _arrayLike, _callback, _thisArg, _logic )
{
    var asString = ( "charAt" in _arrayLike ) && ( "substr" in _arrayLike );
    for ( var i = 0, len = _arrayLike.length >>> 0, value, result; i < len; ++i )
    {
        if ( asString || ( i in _arrayLike ) )
        {
            result = _callback.call( _thisArg, value = asString ? _arrayLike.charAt( i ) : _arrayLike[i], i, _arrayLike );
            if ( _logic( value, i, result ) === true )
                break;
        }
    }
}

/**
 * Polyfills for {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array Array}.
 * @class module:barejs/polyfill.Array
 */

/*istanbul ignore else: We test with __ES__ set to 3*/
if ( __ES__ < 5 )
{
    /**
     * Enumerate all values in the array
     * @this {Array}
     * @param {function} _callback The callback to call for each value
     * @param {object} [_thisArg] Optional: the context in which the callback should be invoked
     */
    proto.forEach = function forEach( _callback/*, _thisArg (method has length 1)*/ )
    {
        iterate( toObject( this, forEach ), ensureCallable( _callback ), arguments[1], function() {/*no logic*/} );
    };

    /**
     * Check if callback returns true for every element
     * @this {Array}
     * @param {function} _callback The callback to test each value
     * @param {object} [_thisArg] Optional: the context in which the callback should be invoked
     * @returns {boolean} True if the callback returns true for each element, false otherwise.
     */
    proto.every = function every( _callback/*, _thisArg (method has length 1)*/ )
    {
        var result = true;
        iterate( toObject( this, every ), ensureCallable( _callback ), arguments[1], function( _v, _i, _r )
        {
            // If the callback returned a falsey value
            if ( !_r )
            {
                // The every statement doesn't hold true
                result = false;
                // Break execution
                return true;
            }
        } );
        return result;
    };

    /**
     * Check if callback returns true for any element
     * @this {Array}
     * @param {function} _callback The callback to test each value
     * @param {object} [_thisArg] Optional: the context in which the callback should be invoked
     * @returns {boolean} True if the callback returns true for at least one element, false otherwise.
     */
    proto.some = function some( _callback/*, _thisArg (method has length 1)*/ )
    {
        var result = false;
        iterate( toObject( this, some ), ensureCallable( _callback ), arguments[1], function( _v, _i, _r )
        {
            // If the callback returned a thruthy value, the some statement is true (shortcuted to return true for breaking)
            if ( _r )
                return ( result = true );
        } );
        return result;
    };

    /**
     * Creates a new array with only the elements matching the provided function.
     * @this {Array}
     * @param {function} _callback The callback to test each value.
     * @param {object} [_thisArg] Optional: the context in which the callback should be invoked
     * @returns {Array} A new array containing the result of callback per element.
     */
    proto.filter = function filter( _callback/*, _thisArg (method has length 1)*/ )
    {
        var result = [];
        iterate( toObject( this, filter ), ensureCallable( _callback ), arguments[1], function( _v, _i, _r )
        {
            // If the callback returned a thruthy value, add the value to the result
            if ( _r )
                result.push( _v );
        } );
        return result;
    };

    /**
     * Creates a new array with the results of calling a provided function on every element in this array.
     * @this {Array}
     * @param {function} _callback The callback to test each value
     * @param {object} [_thisArg] Optional: the context in which the callback should be invoked
     * @returns {Array} A new array containing the result of callback per element.
     */
    proto.map = function map( _callback/*, _thisArg (method has length 1)*/ )
    {
        var o = toObject( this, map ), result = new Array( o.length >>> 0 );
        iterate( o, ensureCallable( _callback ), arguments[1], function( _v, _i, _r )
        {
            result[_i] = _r;
        } );
        return result;
    };

    /**
     * Returns the first index at which a given element can be found in the array, or -1 if it is not present.
     * @this {Array}
     * @param {object} _searchElement Element to locate in the array.
     * @param {number} [_fromIndex=0] Optional: The index to start the search at. Default: 0
     *      If the index is greater than or equal to the array's length, -1 is returned, which means
     *      the array will not be searched. If the provided index value is a negative number, it is
     *      taken as the offset from the end of the array. Note: if the provided index is negative,
     *      the array is still searched from front to back. If the calculated index is less than 0,
     *      then the whole array will be searched.
     * @returns {number} The first index at which a given element can be found in the array, or -1 if it is not present.
     */
    proto.indexOf = function indexOf( _searchElement/*, _fromIndex*/ )
    {
        var t = toObject( this, indexOf ), len = t.length >>> 0, i = 0;

        if ( len < 1 )
            return -1;

        if ( arguments.length >= 2 )
        {
            if ( ( i = arguments[1] >> 0 ) < 0 )
                i = Math.max( 0, len + i );
        }

        for ( ; i < len; ++i )
            if ( ( i in t ) && ( t[i] === _searchElement ) )
                return i;

        return -1;
    };

    /**
     * Returns the last index at which a given element can be found in the array, or -1 if it is not present.
     * The array is searched backwards, starting at fromIndex.
     * @this {Array}
     * @param {object} _searchElement Element to locate in the array.
     * @param {number} [_fromIndex=-1] Optional: The index at which to start searching backwards.
     *      Defaults to the array's length - 1, i.e. the whole array will be searched. If the index is
     *      greater than or equal to the length of the array, the whole array will be searched.
     *      If negative, it is taken as the offset from the end of the array. Note that even when
     *      the index is negative, the array is still searched from back to front. If the calculated
     *      index is less than 0, -1 is returned, i.e. the array will not be searched.
     * @returns {number} The last index at which a given element can be found in the array, or -1 if it is not present.
     */
    proto.lastIndexOf = function lastIndexOf( _searchElement/*, _fromIndex*/ )
    {
        var t = toObject( this, lastIndexOf ), len = t.length >>> 0, i = len - 1;

        if ( len < 1 )
            return -1;

        if ( arguments.length >= 2 )
        {
            if ( ( i = Math.min( i, arguments[1] >> 0 ) ) < 0 )
                i += len;
        }

        for ( ; i >= 0; --i )
            if ( ( i in this ) && ( this[i] === _searchElement ) )
                return i;

        return -1;
    };

    /**
     * The reduce() method applies a function against an accumulator and each value of the
     * array (from left-to-right) has to reduce it to a single value.
     * @this {Array}
     * @param {function} _callback The callback to call for each value, taking 4 arguments:
     *              previousValue
     *                  The value previously returned in the last invocation of the callback, or initialValue, if supplied. (See below.)
     *              currentValue
     *                  The current element being processed in the array.
     *              index
     *                  The index of the current element being processed in the array.
     *              array
     *                  The array reduce was called upon.
     * @param {object} [_initialValue] Optional: a value to pass to the first callback.
     */
    proto.reduce = function reduce( _callback/*, _initialValue*/ )
    {
        var t = toObject( this, reduce ), len = t.length >>> 0, i = ensureCallable( _callback, 0 ), value;

        if ( arguments.length >= 2 )
        {
            value = arguments[1];
        }
        else
        {
            while ( ( i < len ) && !( i in t ) )
                ++i;

            if ( i >= len )
                throw new TypeError( "Reduce of empty array with no initial value" );
            value = t[i++];
        }
        for (; i < len; ++i)
        {
            if ( i in t )
                value = _callback( value, t[i], i, t );
        }
        return value;
    };

    /**
     * The reduceRight() method applies a function against an accumulator and each value of the
     * array (from right-to-left) has to reduce it to a single value.
     * @this {Array}
     * @param {function} _callback The callback to call for each value, taking 4 arguments:
     *              previousValue
     *                  The value previously returned in the last invocation of the callback, or initialValue, if supplied. (See below.)
     *              currentValue
     *                  The current element being processed in the array.
     *              index
     *                  The index of the current element being processed in the array.
     *              array
     *                  The array reduce was called upon.
     * @param {object} [_initialValue] Optional: a value to pass to the first callback.
     */
    proto.reduceRight = function reduceRight( _callback/*, _initialValue*/ )
    {
        var t = toObject( this, reduceRight ), len = t.length >>> 0, i = ensureCallable( _callback, len - 1 ), value;

        if ( arguments.length >= 2 )
        {
            value = arguments[1];
        }
        else
        {
            while ( ( i >= 0 ) && !( i in t ) )
                --i;

            if ( i < 0 )
                throw new TypeError( "Reduce of empty array with no initial value" );
            value = t[i--];
        }
        for (; i >= 0; --i)
        {
            if ( i in t )
                value = _callback( value, t[i], i, t );
        }
        return value;
    };

    /**
     * Check if an object is an array.
     * @param _arg The object to check.
     * @returns {boolean} true if an object is an array, false if it is not.
     */
    stat.isArray = function isArray( _arg )
    {
        return toString.call( _arg ) === "[object Array]";
    };
// End of ES5 polyfill scope
}

/*istanbul ignore else: We test with __ES__ set to 3 */
if ( __ES__ < 6 )
{
    /**
     * Find a value in the array
     * @param {function} _callback The callback to test each value in the array. If the value matches, it should return true.
     * @param {object} [_thisArg] Optional: the context in which the callback should be invoked
     * @returns the found value or undefined if not found.
     */
    proto.find = function find( _callback/*, _thisArg (method has length 1)*/ )
    {
        var result = void undefined;
        iterate( toObject( this, find ), ensureCallable( _callback ), arguments[1], function( _v, _i, _r )
        {
            // If the callback returned a thruthy value, the result is found
            if ( _r )
            {
                result = _v;
                // Break the loop
                return true;
            }
        } );
        return result;
    };

    /**
     * Find a value in the array
     * @param {function} _callback The callback to test each value in the array. If the value matches, it should return true.
     * @param {object} [_thisArg] Optional: the context in which the callback should be invoked
     * @returns {number} the found index or -1 if not found.
     */
    proto.findIndex = function findIndex( _callback/*, _thisArg (method has length 1)*/ )
    {
        var result = -1;
        iterate( toObject( this, findIndex ), ensureCallable( _callback ), arguments[1], function( _v, _i, _r )
        {
            // If the callback returned a thruthy value, the result is found
            if ( _r )
            {
                result = _i;
                // Break the loop
                return true;
            }
        } );
        return result;
    };

    /**
     * The fill() method fills all the elements of an array from a start index to an end index with a static value.
     * @param _value The value to set to each index
     * @param {number} [_start=0] Optional: the index to start filling (inclusive)
     * If _start is negative, it is treated as length + _start.
     * @param {number} [_end] Optional: the index at which to stop filling (exclusive)
     * If _end is negative, it is treated as length + _end.
     */
    proto.fill = function fill( _value/*, _start, _end*/ )
    {
        var t = toObject( this, fill ), len = t.length >>> 0, i = arguments[1] >> 0, end = arguments[2];

        if ( i < 0 )
            i = Math.max( 0, i + len );
        if ( end === undefined )
            end = len;
        else if ( end < 0 )
            end = Math.max( 0, end + len );

        for ( ; i < end; ++i )
            t[i] = _value;

        return t;
    };

    /**
     * The Array.of() method creates a new Array instance with a variable number of arguments,
     * regardless of number or type of the arguments.
     * @param {...any} _value Any number of values that will be the content of the array.
     * @returns {Array} The created Array.
     */
    stat.of = function of()
    {
        var C = this;
        var args = arguments;
        var len = args.length;
        var result = isCallable( C ) ? Object( new C( len ) ) : new Array( len );
        for ( var  i = 0; i < len; ++i )
            result[i] = args[i];
        return result;
    };

    /**
     * The Array.from() method creates a new Array instance from an array-like or iterable object.
     * @param {object} _arrayLike An array-like or iterable object to convert to an array.
     * @param {function} [_mapFn] Optional. Map function to call on every element of the array.
     * @param {object} [_thisArg] Optional. Value to use as this when executing mapFn.
     * @returns {Array} The created Array.
     */
    stat.from = function from( _arrayLike/*, _mapFn, _thisArg*/ )
    {
        var C = this;
        var items = toObject( _arrayLike );
        var mapFn = typeof arguments[1] !== "undefined" ? ensureCallable( arguments[1] ) : null;
        var thisArg = arguments[2];
        // Iterators can't be emulated, but add specific logic for Map and Set so those are supported
        // Note: check both for a potential global and the polyfill separately:
        // NMap and Map MAY point to the same function, but don't have to in every environment (!).
        var isMap = items instanceof NMap;
        // Normalize to an Array, source. Chances are high we can just return this Array, or map it in place.
        var source;
        var i, len;

        if ( mapFn )
        {
            if ( thisArg === undefined )
                thisArg = null;
            else if ( thisArg !== null )
                thisArg = Object( thisArg );
        }

        var it = isCallable( items.next ) ? items : ObjectPolyfill.getIterator( items );
        if ( it )
        {
            source = [];
            for ( var cur = it.next(); !cur.done; cur = it.next() )
                source.push( cur.value );
            len = source.length;
        }
        // IE11's native map and set support forEach, but not iterators. Emulate using forEach.
        else if ( ( isMap || ( items instanceof NSet ) ) && isCallable( items.forEach ) )
        {
            i = 0;
            len = Math.floor( items.size ) || 0;
            source = new Array( len );
            items.forEach( function( _value, _key )
            {
                var entry;
                if ( isMap )
                {
                    entry = new Array( 2 );
                    entry[0] = _key;
                    entry[1] = _value;
                }
                else
                {
                    entry = _value;
                }
                source[ i++ ] = entry;
            } );
        }
        if ( !source )
        {
            var asString = ( "charAt" in items ) && ( "substr" in items );
            len = Math.floor( items.length ) || 0;
            source = new Array( len );

            for ( i = 0; i < len; ++i )
                source[i] = asString ? items.charAt( i ) : items[i];
        }

        // We already have an Array (source), only create a new Object if we have a Constructor as context
        var result = isCallable( C ) && C !== Array ? Object( new C( len ) ) : source;

        if ( mapFn || result !== source )
        {
            for ( i = 0; i < len; ++i )
                result[i] = mapFn ? mapFn.call( thisArg, source[i], i ) : source[i];
        }

        return result;
    };
// End of ES6 polyfill scope
}

/*istanbul ignore else: We test with __ES__ set to 3*/
if ( __ES__ < 7 )
{
    /**
     * The includes() method determines whether an array includes a certain element, returning true or false as appropriate.
     * The array is searched forwards, starting at fromIndex (defaults to 0).
     * @param {object} _searchElement Element to locate in the array.
     * @param {object} [_fromIndex=0] Optional: The index to start the search at. Default: 0
     *      If the index is greater than or equal to the array's length, -1 is returned, which means
     *      the array will not be searched. If the provided index value is a negative number, it is
     *      taken as the offset from the end of the array. Note: if the provided index is negative,
     *      the array is still searched from front to back. If the calculated index is less than 0,
     *      then the whole array will be searched.
     * @returns {boolean} True if the element was found, false otherwise.
     */
    proto.includes = function includes( _searchElement/*, _fromIndex*/ )
    {
        var t = toObject( this, includes ), len = t.length >>> 0, i = 0;

        if ( len < 1 )
            return false;

        if ( arguments.length > 1 )
        {
            if ( ( i = arguments[1] >> 0 ) < 0 )
                i = Math.max( 0, len + i );
        }

        for ( ; i < len; ++i )
            if ( ( t[i] === _searchElement ) || ( _searchElement !== _searchElement && t[i] !== t[i] ) )
                return true;

        return false;
    };
// End of ES7 polyfill scope
}

ObjectPolyfill.polyfill( Array, stat, proto, exports, "Array" );

// End of module
}( Array, require( "./Object" ), require( "../NMap" ), require( "../NSet" ) ) );