// Licensed Materials - Property of IBM
//
// IBM Watson Analytics
//
// (C) Copyright IBM Corp. 2015
//
// US Government Users Restricted Rights - Use, duplication or
// disclosure restricted by GSA ADP Schedule Contract with IBM Corp.
( function( Math, RegExp, String, ObjectPolyfill )
{
"use strict";
var strUndef = "undefined";
/**
* Polyfills for {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String String}.
* @class module:barejs/polyfill.String
*/
/** @lends module:barejs/polyfill.String */
var stat = {},
/** @lends module:barejs/polyfill.String# */
proto = {};
/*jshint bitwise:false*/
function stringContext( _context, _name )
{
if ( ( typeof _context === strUndef ) || ( _context === null ) )
throw new TypeError( "String.prototype." + _name + " called on null or undefined" );
return String( _context );
}
function toSearch( _search, _name )
{
if ( _search instanceof RegExp )
throw new TypeError( "First argument to String.prototype." + _name + " must not be a regular expression" );
return String( _search );
}
function toNumber( _value, _min, _default, _max )
{
if ( isNaN( _value = Math.trunc( _value ) ) )
return _default;
return _value < _min ? _min : ( _value > _max ? _max : _value );
}
/*istanbul ignore else: We test with __ES__ set to 3*/
if ( __ES__ < 6 )
{
/**
* Check if the string starts with the other string
* @param {string} _search The part to search for
* @param {number} [_start=0] Optional: The position in this string at which to begin searching for _search; defaults to 0.
* @returns {boolean} True if the string starts with search, false otherwise.
*/
proto.startsWith = function startsWith( _search/*, _start*/ )
{
var str = stringContext( this, "startsWith" ),
pos = toNumber( arguments[1], 0, 0, str.length );
// Using lastIndexOf ensures we don't search the whole string for _search, just at the requested pos index going back.
return str.lastIndexOf( toSearch( _search, "startsWith" ), pos ) === pos;
};
/**
* Check if the string ends with the other string
* @param {string} _search The part to search for
* @param {number} [_limit] Optional: Search within this string as if this string were only this long;
* defaults to this string's actual length, clamped within the range established by this string's length.
* @returns {boolean} True if the string ends with search, false otherwise.
*/
proto.endsWith = function endsWith( _search/*, _limit*/ )
{
var str = stringContext( this, "endsWith" ),
// We need to start matching at this position
pos = toNumber( arguments[1], 0, str.length, str.length ) - ( _search = toSearch( _search, "endsWith" ) ).length;
// Using indexOf ensures we don't search the whole string for _search, just at the requested end index going forward.
return ( pos >= 0 ) && str.indexOf( _search, pos ) === pos;
};
( function( _whitespace )
{
var reTrim = /^\s+|\s+$/g;
var reTrimStart = /^\s+/;
var reTrimEnd = /\s+$/;
/*
* Attempt to sniff out regular expression engines that do not have all whitespace under the \s character class.
* If so, build the same regex as above, but with our expanded whitespace class.
*/
/*istanbul ignore if: This check only fails in very old IE versions (<IE6)*/
if ( _whitespace.match( /[^\s]/ ) )
{
reTrim = new RegExp( "^[\\s" + _whitespace + "]+|[\\s" + _whitespace + "]+$", "g" );
reTrimStart = new RegExp( "^[\\s" + _whitespace + "]+" );
reTrimEnd = new RegExp( "[\\s" + _whitespace + "]+$" );
}
/**
* The trim() method removes whitespace from both ends of a string. Whitespace in this context is
* all the whitespace characters (space, tab, no-break space, etc.) and all the line terminator
* characters (LF, CR, etc.).
* @returns {string} The trimmed string.
*/
proto.trim = function trim()
{
// jshint validthis:true
return stringContext( this, "trim" ).replace( reTrim, "" );
};
/**
* The trimStart() method removes whitespace from the beginning of a string. Whitespace in this context is
* all the whitespace characters (space, tab, no-break space, etc.) and all the line terminator
* characters (LF, CR, etc.).
* @returns {string} The trimmed string.
*/
proto.trimStart = proto.trimLeft = function trimStart()
{
// jshint validthis:true
return stringContext( this, "trimStart" ).replace( reTrimStart, "" );
};
/**
* The trimEnd() method removes whitespace from the end of a string. Whitespace in this context is
* all the whitespace characters (space, tab, no-break space, etc.) and all the line terminator
* characters (LF, CR, etc.).
* @returns {string} The trimmed string.
*/
proto.trimEnd = proto.trimRight = function trimEnd()
{
// jshint validthis:true
return stringContext( this, "trimEnd" ).replace( reTrimEnd, "" );
};
}( String.fromCharCode(
// \u00A0, NO-BREAK SPACE
160,
// \u1680, OGHAM SPACE MARK
5760,
// \u2000..\u200A, EN QUAD..HAIR SPACE
8192, 8193, 8194, 8195, 8196, 8197, 8198, 8199, 8200, 8201, 8202,
// \u2028, LINE SEPARATOR
8232,
// \u2029, PARAGRAPH SEPARATOR
8233,
// \u202F, NARROW NO-BREAK SPACE
8239,
// \u205F, MEDIUM MATHEMATICAL SPACE
8287,
// \u3000, IDEOGRAPHIC SPACE
12288
) ) );
( function()
{
// Ensuring count is a 31-bit integer allows us to heavily optimise the main part of the method.
// Besides that, browsers that will need this polyfill can't handle strings 1 << 28 chars or longer.
var LIMIT = 1 << 28;
/**
* The repeat() method constructs and returns a new string which contains the specified number
* of copies of the string on which it was called, concatenated together.
* @param {number} _count The amount of times to repeat the number.
* @returns {string} The string, repeated.
*/
proto.repeat = function repeat( _count )
{
// jshint validthis:true
var rpt = "",
str = stringContext( this, "repeat" ),
count = Math.floor( _count ) || 0;
if ( count < 0 )
throw new RangeError( "repeat count must be non-negative" );
if ( count === Infinity )
throw new RangeError( "repeat count must be less than infinity" );
// If either string.length or count is 0, we'll get length 0
var len = str.length * count;
if ( len >= LIMIT )
throw new RangeError( "repeat count must not overflow maximum string size" );
if ( len > 0 )
{
// Optimised: concatenates str instead of rpt, to perform the operation with the least
// amount of string concatenations possible.
for (;;)
{
if ( ( count & 1 ) === 1 )
rpt += str;
count >>>= 1;
if ( count === 0 )
break;
str += str;
}
}
return rpt;
};
}() );
/**
* The codePointAt() method returns a non-negative integer that is the UTF-16 encoded code point value.
* @param {number} _position The index at which the code point should be read
* @returns {number} The code point value, or undefined if _position is out of range.
*/
proto.codePointAt = function codePointAt( _position )
{
var str = stringContext( this, "codePointAt" ),
len = str.length,
// `ToInteger`
i = Math.floor( _position ) || 0,
result;
// Account for out-of-bounds indices:
if ( i >= 0 && i < len )
{
// Get the first code unit; increment index afterwards
result = str.charCodeAt( i++ );
// check if it’s the start of a surrogate pair
// high surrogate && there is a next code unit
if ( ( result >= 0xD800 ) && ( result <= 0xDBFF ) && ( i < len ) )
{
var pair = str.charCodeAt( i );
if ( ( pair >= 0xDC00 ) && ( pair <= 0xDFFF ) ) // low surrogate
result = ( result - 0xD800 ) * 0x400 + pair - 0xDC00 + 0x10000;
}
}
return result;
};
/**
* Create a String from any number of codepoint values
* @returns {string} The created string
*/
stat.fromCodePoint = function fromCodePoint( _firstCodePoint )
{
var codeUnits = [],
result = "";
for ( var i = 0, len = arguments.length; i < len; ++i )
{
var codePoint = +( arguments[i] );
if (
( !isFinite( codePoint ) ) || // `NaN`, `+Infinity`, or `-Infinity`
( codePoint < 0 ) || ( codePoint > 0x10FFFF ) || // not a valid Unicode code point
( Math.floor( codePoint ) !== codePoint ) // not an integer
)
{
throw new RangeError( "Invalid code point: " + codePoint );
}
if ( codePoint <= 0xFFFF )
{
// BMP code point
codeUnits.push( codePoint );
}
else
{
// Astral code point; split in surrogate halves
codePoint -= 0x10000;
var highSurrogate = ( codePoint >> 10 ) + 0xD800;
var lowSurrogate = ( codePoint % 0x400 ) + 0xDC00;
codeUnits.push( highSurrogate, lowSurrogate );
}
if ( ( i + 1 === len ) || ( codeUnits.length > 0x4000 ) )
{
result += String.fromCharCode.apply( String, codeUnits );
codeUnits.length = 0;
}
}
return result;
};
/**
* Check if the string includes the other string
* @param {string} _search The part to search for
* @param {number} [_position=0] Optional: The index to start searching at. Defaults to 0.
* @returns {boolean} True if the string includes search, false otherwise.
*/
proto.includes = function includes( _search/*, _position*/ )
{
var str = stringContext( this, "includes" ),
pos = toNumber( arguments[1], 0, 0, str.length );
return str.indexOf( toSearch( _search, "includes" ), pos ) >= 0;
};
// End of ES6 polyfill scope
}
/*istanbul ignore else: We test with __ES__ set to 3*/
if ( __ES__ < 7 )
{
/**
* The padStart() method pads the current string with a given string (eventually repeated) so that the resulting string reaches a given length.
* The pad is applied from the start (left) of the current string.
* @param {number} _targetLength The length of the resulting string once the current string has been padded.
* If this parameter is smaller than the current string's length, the current string will be returned as it is.
* @param {string} [_padString=" "] The string to pad the current string with.
* If this string is too long, it will be truncated and the left-most part will be applied.
* The default value for this parameter is " " (U+0020).
*/
proto.padStart = function padStart( _targetLength/*, _padString*/ )
{
var str = stringContext( this, "padStart" ),
pad = arguments[1],
len = Math.trunc( _targetLength ) || 0,
add = len - str.length,
pLen,
pre;
pad = typeof pad === strUndef ? " " : String( pad );
pLen = pad.length;
if ( ( add > 0 ) && ( pLen > 0 ) )
{
pre = pad.repeat( Math.floor( add / pLen ) );
add %= pLen;
if ( add > 0 )
pre += pad.substr( 0, add );
str = pre + str;
}
return str;
};
/**
* The padEnd() method pads the current string with a given string (eventually repeated) so that the resulting string reaches a given length.
* The pad is applied from the end (right) of the current string.
* @param {number} _targetLength The length of the resulting string once the current string has been padded.
* If this parameter is smaller than the current string's length, the current string will be returned as it is.
* @param {string} [_padString=" "] The string to pad the current string with.
* If this string is too long, it will be truncated and the left-most part will be applied.
* The default value for this parameter is " " (U+0020).
*/
proto.padEnd = function padEnd( _targetLength/*, _padString*/ )
{
var str = stringContext( this, "padEnd" ),
pad = arguments[1],
len = Math.trunc( _targetLength ) || 0,
add = len - str.length,
pLen,
post;
pad = typeof pad === strUndef ? " " : String( pad );
pLen = pad.length;
if ( ( add > 0 ) && ( pLen > 0 ) )
{
post = pad.repeat( Math.floor( add / pLen ) );
add %= pLen;
if ( add > 0 )
post += pad.substr( 0, add );
str += post;
}
return str;
};
}
ObjectPolyfill.polyfill( String, stat, proto, exports, "String" );
// End of module
}( Math, RegExp, String, require( "./Object" ) ) );