polyfill_String.js.html 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="utf-8">
  5. <title>JSDoc: Source: polyfill/String.js</title>
  6. <script src="scripts/prettify/prettify.js"> </script>
  7. <script src="scripts/prettify/lang-css.js"> </script>
  8. <!--[if lt IE 9]>
  9. <script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
  10. <![endif]-->
  11. <link type="text/css" rel="stylesheet" href="styles/prettify-tomorrow.css">
  12. <link type="text/css" rel="stylesheet" href="styles/jsdoc-default.css">
  13. </head>
  14. <body>
  15. <div id="main">
  16. <h1 class="page-title">Source: polyfill/String.js</h1>
  17. <section>
  18. <article>
  19. <pre class="prettyprint source linenums"><code>// Licensed Materials - Property of IBM
  20. //
  21. // IBM Watson Analytics
  22. //
  23. // (C) Copyright IBM Corp. 2015
  24. //
  25. // US Government Users Restricted Rights - Use, duplication or
  26. // disclosure restricted by GSA ADP Schedule Contract with IBM Corp.
  27. ( function( Math, RegExp, String, ObjectPolyfill )
  28. {
  29. "use strict";
  30. var strUndef = "undefined";
  31. /**
  32. * Polyfills for {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String String}.
  33. * @class module:barejs/polyfill.String
  34. */
  35. /** @lends module:barejs/polyfill.String */
  36. var stat = {},
  37. /** @lends module:barejs/polyfill.String# */
  38. proto = {};
  39. /*jshint bitwise:false*/
  40. function stringContext( _context, _name )
  41. {
  42. if ( ( typeof _context === strUndef ) || ( _context === null ) )
  43. throw new TypeError( "String.prototype." + _name + " called on null or undefined" );
  44. return String( _context );
  45. }
  46. function toSearch( _search, _name )
  47. {
  48. if ( _search instanceof RegExp )
  49. throw new TypeError( "First argument to String.prototype." + _name + " must not be a regular expression" );
  50. return String( _search );
  51. }
  52. function toNumber( _value, _min, _default, _max )
  53. {
  54. if ( isNaN( _value = Math.trunc( _value ) ) )
  55. return _default;
  56. return _value &lt; _min ? _min : ( _value > _max ? _max : _value );
  57. }
  58. /*istanbul ignore else: We test with __ES__ set to 3*/
  59. if ( __ES__ &lt; 6 )
  60. {
  61. /**
  62. * Check if the string starts with the other string
  63. * @param {string} _search The part to search for
  64. * @param {number} [_start=0] Optional: The position in this string at which to begin searching for _search; defaults to 0.
  65. * @returns {boolean} True if the string starts with search, false otherwise.
  66. */
  67. proto.startsWith = function startsWith( _search/*, _start*/ )
  68. {
  69. var str = stringContext( this, "startsWith" ),
  70. pos = toNumber( arguments[1], 0, 0, str.length );
  71. // Using lastIndexOf ensures we don't search the whole string for _search, just at the requested pos index going back.
  72. return str.lastIndexOf( toSearch( _search, "startsWith" ), pos ) === pos;
  73. };
  74. /**
  75. * Check if the string ends with the other string
  76. * @param {string} _search The part to search for
  77. * @param {number} [_limit] Optional: Search within this string as if this string were only this long;
  78. * defaults to this string's actual length, clamped within the range established by this string's length.
  79. * @returns {boolean} True if the string ends with search, false otherwise.
  80. */
  81. proto.endsWith = function endsWith( _search/*, _limit*/ )
  82. {
  83. var str = stringContext( this, "endsWith" ),
  84. // We need to start matching at this position
  85. pos = toNumber( arguments[1], 0, str.length, str.length ) - ( _search = toSearch( _search, "endsWith" ) ).length;
  86. // Using indexOf ensures we don't search the whole string for _search, just at the requested end index going forward.
  87. return ( pos >= 0 ) &amp;&amp; str.indexOf( _search, pos ) === pos;
  88. };
  89. ( function( _whitespace )
  90. {
  91. var reTrim = /^\s+|\s+$/g;
  92. var reTrimStart = /^\s+/;
  93. var reTrimEnd = /\s+$/;
  94. /*
  95. * Attempt to sniff out regular expression engines that do not have all whitespace under the \s character class.
  96. * If so, build the same regex as above, but with our expanded whitespace class.
  97. */
  98. /*istanbul ignore if: This check only fails in very old IE versions (&lt;IE6)*/
  99. if ( _whitespace.match( /[^\s]/ ) )
  100. {
  101. reTrim = new RegExp( "^[\\s" + _whitespace + "]+|[\\s" + _whitespace + "]+$", "g" );
  102. reTrimStart = new RegExp( "^[\\s" + _whitespace + "]+" );
  103. reTrimEnd = new RegExp( "[\\s" + _whitespace + "]+$" );
  104. }
  105. /**
  106. * The trim() method removes whitespace from both ends of a string. Whitespace in this context is
  107. * all the whitespace characters (space, tab, no-break space, etc.) and all the line terminator
  108. * characters (LF, CR, etc.).
  109. * @returns {string} The trimmed string.
  110. */
  111. proto.trim = function trim()
  112. {
  113. // jshint validthis:true
  114. return stringContext( this, "trim" ).replace( reTrim, "" );
  115. };
  116. /**
  117. * The trimStart() method removes whitespace from the beginning of a string. Whitespace in this context is
  118. * all the whitespace characters (space, tab, no-break space, etc.) and all the line terminator
  119. * characters (LF, CR, etc.).
  120. * @returns {string} The trimmed string.
  121. */
  122. proto.trimStart = proto.trimLeft = function trimStart()
  123. {
  124. // jshint validthis:true
  125. return stringContext( this, "trimStart" ).replace( reTrimStart, "" );
  126. };
  127. /**
  128. * The trimEnd() method removes whitespace from the end of a string. Whitespace in this context is
  129. * all the whitespace characters (space, tab, no-break space, etc.) and all the line terminator
  130. * characters (LF, CR, etc.).
  131. * @returns {string} The trimmed string.
  132. */
  133. proto.trimEnd = proto.trimRight = function trimEnd()
  134. {
  135. // jshint validthis:true
  136. return stringContext( this, "trimEnd" ).replace( reTrimEnd, "" );
  137. };
  138. }( String.fromCharCode(
  139. // \u00A0, NO-BREAK SPACE
  140. 160,
  141. // \u1680, OGHAM SPACE MARK
  142. 5760,
  143. // \u2000..\u200A, EN QUAD..HAIR SPACE
  144. 8192, 8193, 8194, 8195, 8196, 8197, 8198, 8199, 8200, 8201, 8202,
  145. // \u2028, LINE SEPARATOR
  146. 8232,
  147. // \u2029, PARAGRAPH SEPARATOR
  148. 8233,
  149. // \u202F, NARROW NO-BREAK SPACE
  150. 8239,
  151. // \u205F, MEDIUM MATHEMATICAL SPACE
  152. 8287,
  153. // \u3000, IDEOGRAPHIC SPACE
  154. 12288
  155. ) ) );
  156. ( function()
  157. {
  158. // Ensuring count is a 31-bit integer allows us to heavily optimise the main part of the method.
  159. // Besides that, browsers that will need this polyfill can't handle strings 1 &lt;&lt; 28 chars or longer.
  160. var LIMIT = 1 &lt;&lt; 28;
  161. /**
  162. * The repeat() method constructs and returns a new string which contains the specified number
  163. * of copies of the string on which it was called, concatenated together.
  164. * @param {number} _count The amount of times to repeat the number.
  165. * @returns {string} The string, repeated.
  166. */
  167. proto.repeat = function repeat( _count )
  168. {
  169. // jshint validthis:true
  170. var rpt = "",
  171. str = stringContext( this, "repeat" ),
  172. count = Math.floor( _count ) || 0;
  173. if ( count &lt; 0 )
  174. throw new RangeError( "repeat count must be non-negative" );
  175. if ( count === Infinity )
  176. throw new RangeError( "repeat count must be less than infinity" );
  177. // If either string.length or count is 0, we'll get length 0
  178. var len = str.length * count;
  179. if ( len >= LIMIT )
  180. throw new RangeError( "repeat count must not overflow maximum string size" );
  181. if ( len > 0 )
  182. {
  183. // Optimised: concatenates str instead of rpt, to perform the operation with the least
  184. // amount of string concatenations possible.
  185. for (;;)
  186. {
  187. if ( ( count &amp; 1 ) === 1 )
  188. rpt += str;
  189. count >>>= 1;
  190. if ( count === 0 )
  191. break;
  192. str += str;
  193. }
  194. }
  195. return rpt;
  196. };
  197. }() );
  198. /**
  199. * The codePointAt() method returns a non-negative integer that is the UTF-16 encoded code point value.
  200. * @param {number} _position The index at which the code point should be read
  201. * @returns {number} The code point value, or undefined if _position is out of range.
  202. */
  203. proto.codePointAt = function codePointAt( _position )
  204. {
  205. var str = stringContext( this, "codePointAt" ),
  206. len = str.length,
  207. // `ToInteger`
  208. i = Math.floor( _position ) || 0,
  209. result;
  210. // Account for out-of-bounds indices:
  211. if ( i >= 0 &amp;&amp; i &lt; len )
  212. {
  213. // Get the first code unit; increment index afterwards
  214. result = str.charCodeAt( i++ );
  215. // check if it’s the start of a surrogate pair
  216. // high surrogate &amp;&amp; there is a next code unit
  217. if ( ( result >= 0xD800 ) &amp;&amp; ( result &lt;= 0xDBFF ) &amp;&amp; ( i &lt; len ) )
  218. {
  219. var pair = str.charCodeAt( i );
  220. if ( ( pair >= 0xDC00 ) &amp;&amp; ( pair &lt;= 0xDFFF ) ) // low surrogate
  221. result = ( result - 0xD800 ) * 0x400 + pair - 0xDC00 + 0x10000;
  222. }
  223. }
  224. return result;
  225. };
  226. /**
  227. * Create a String from any number of codepoint values
  228. * @returns {string} The created string
  229. */
  230. stat.fromCodePoint = function fromCodePoint( _firstCodePoint )
  231. {
  232. var codeUnits = [],
  233. result = "";
  234. for ( var i = 0, len = arguments.length; i &lt; len; ++i )
  235. {
  236. var codePoint = +( arguments[i] );
  237. if (
  238. ( !isFinite( codePoint ) ) || // `NaN`, `+Infinity`, or `-Infinity`
  239. ( codePoint &lt; 0 ) || ( codePoint > 0x10FFFF ) || // not a valid Unicode code point
  240. ( Math.floor( codePoint ) !== codePoint ) // not an integer
  241. )
  242. {
  243. throw new RangeError( "Invalid code point: " + codePoint );
  244. }
  245. if ( codePoint &lt;= 0xFFFF )
  246. {
  247. // BMP code point
  248. codeUnits.push( codePoint );
  249. }
  250. else
  251. {
  252. // Astral code point; split in surrogate halves
  253. codePoint -= 0x10000;
  254. var highSurrogate = ( codePoint >> 10 ) + 0xD800;
  255. var lowSurrogate = ( codePoint % 0x400 ) + 0xDC00;
  256. codeUnits.push( highSurrogate, lowSurrogate );
  257. }
  258. if ( ( i + 1 === len ) || ( codeUnits.length > 0x4000 ) )
  259. {
  260. result += String.fromCharCode.apply( String, codeUnits );
  261. codeUnits.length = 0;
  262. }
  263. }
  264. return result;
  265. };
  266. /**
  267. * Check if the string includes the other string
  268. * @param {string} _search The part to search for
  269. * @param {number} [_position=0] Optional: The index to start searching at. Defaults to 0.
  270. * @returns {boolean} True if the string includes search, false otherwise.
  271. */
  272. proto.includes = function includes( _search/*, _position*/ )
  273. {
  274. var str = stringContext( this, "includes" ),
  275. pos = toNumber( arguments[1], 0, 0, str.length );
  276. return str.indexOf( toSearch( _search, "includes" ), pos ) >= 0;
  277. };
  278. // End of ES6 polyfill scope
  279. }
  280. /*istanbul ignore else: We test with __ES__ set to 3*/
  281. if ( __ES__ &lt; 7 )
  282. {
  283. /**
  284. * The padStart() method pads the current string with a given string (eventually repeated) so that the resulting string reaches a given length.
  285. * The pad is applied from the start (left) of the current string.
  286. * @param {number} _targetLength The length of the resulting string once the current string has been padded.
  287. * If this parameter is smaller than the current string's length, the current string will be returned as it is.
  288. * @param {string} [_padString=" "] The string to pad the current string with.
  289. * If this string is too long, it will be truncated and the left-most part will be applied.
  290. * The default value for this parameter is " " (U+0020).
  291. */
  292. proto.padStart = function padStart( _targetLength/*, _padString*/ )
  293. {
  294. var str = stringContext( this, "padStart" ),
  295. pad = arguments[1],
  296. len = Math.trunc( _targetLength ) || 0,
  297. add = len - str.length,
  298. pLen,
  299. pre;
  300. pad = typeof pad === strUndef ? " " : String( pad );
  301. pLen = pad.length;
  302. if ( ( add > 0 ) &amp;&amp; ( pLen > 0 ) )
  303. {
  304. pre = pad.repeat( Math.floor( add / pLen ) );
  305. add %= pLen;
  306. if ( add > 0 )
  307. pre += pad.substr( 0, add );
  308. str = pre + str;
  309. }
  310. return str;
  311. };
  312. /**
  313. * The padEnd() method pads the current string with a given string (eventually repeated) so that the resulting string reaches a given length.
  314. * The pad is applied from the end (right) of the current string.
  315. * @param {number} _targetLength The length of the resulting string once the current string has been padded.
  316. * If this parameter is smaller than the current string's length, the current string will be returned as it is.
  317. * @param {string} [_padString=" "] The string to pad the current string with.
  318. * If this string is too long, it will be truncated and the left-most part will be applied.
  319. * The default value for this parameter is " " (U+0020).
  320. */
  321. proto.padEnd = function padEnd( _targetLength/*, _padString*/ )
  322. {
  323. var str = stringContext( this, "padEnd" ),
  324. pad = arguments[1],
  325. len = Math.trunc( _targetLength ) || 0,
  326. add = len - str.length,
  327. pLen,
  328. post;
  329. pad = typeof pad === strUndef ? " " : String( pad );
  330. pLen = pad.length;
  331. if ( ( add > 0 ) &amp;&amp; ( pLen > 0 ) )
  332. {
  333. post = pad.repeat( Math.floor( add / pLen ) );
  334. add %= pLen;
  335. if ( add > 0 )
  336. post += pad.substr( 0, add );
  337. str += post;
  338. }
  339. return str;
  340. };
  341. }
  342. ObjectPolyfill.polyfill( String, stat, proto, exports, "String" );
  343. // End of module
  344. }( Math, RegExp, String, require( "./Object" ) ) );
  345. </code></pre>
  346. </article>
  347. </section>
  348. </div>
  349. <nav>
  350. <h2><a href="index.html">Home</a></h2><h3>Modules</h3><ul><li><a href="module-barejs.html">barejs</a></li><li><a href="module-barejs_polyfill.html">barejs/polyfill</a></li><li><a href="module-barejs_polyfill_Intl.html">barejs/polyfill/Intl</a></li></ul><h3>Classes</h3><ul><li><a href="module-barejs.decl.html">decl</a></li><li><a href="module-barejs.decl-Enum.html">Enum</a></li><li><a href="module-barejs.decl-Interface.html">Interface</a></li><li><a href="module-barejs.decl-SpecialType.html">SpecialType</a></li><li><a href="module-barejs.Destroyable.html">Destroyable</a></li><li><a href="module-barejs.EventArgs.html">EventArgs</a></li><li><a href="module-barejs.Evented.html">Evented</a></li><li><a href="module-barejs.Evented-EventedHandle.html">EventedHandle</a></li><li><a href="module-barejs.Exception.html">Exception</a></li><li><a href="module-barejs_polyfill.Array.html">Array</a></li><li><a href="module-barejs_polyfill.Date.html">Date</a></li><li><a href="module-barejs_polyfill.EntryStore.html">EntryStore</a></li><li><a href="module-barejs_polyfill.EntryStore.Iterator.html">Iterator</a></li><li><a href="module-barejs_polyfill.Function.html">Function</a></li><li><a href="module-barejs_polyfill.Map.html">Map</a></li><li><a href="module-barejs_polyfill.Map-MapIterator.html">MapIterator</a></li><li><a href="module-barejs_polyfill.Math.html">Math</a></li><li><a href="module-barejs_polyfill.Number.html">Number</a></li><li><a href="module-barejs_polyfill.Object.html">Object</a></li><li><a href="module-barejs_polyfill.Promise.html">Promise</a></li><li><a href="module-barejs_polyfill.Set.html">Set</a></li><li><a href="module-barejs_polyfill.Set-SetIterator.html">SetIterator</a></li><li><a href="module-barejs_polyfill.String.html">String</a></li><li><a href="module-barejs_polyfill.Symbol.html">Symbol</a></li><li><a href="module-barejs_polyfill.WeakMap.html">WeakMap</a></li><li><a href="module-barejs_polyfill.WeakSet.html">WeakSet</a></li><li><a href="module-barejs_polyfill_Intl.DateTimeFormat.html">DateTimeFormat</a></li><li><a href="module-barejs_polyfill_Intl.DateTimeFormat-DateTimeFormatOptions.html">DateTimeFormatOptions</a></li><li><a href="module-barejs_polyfill_Intl.NumberFormat.html">NumberFormat</a></li><li><a href="module-barejs_polyfill_Intl.NumberFormat-NumberFormatOptions.html">NumberFormatOptions</a></li><li><a href="module-barejs_polyfill_Intl-Format.html">Format</a></li></ul>
  351. </nav>
  352. <br class="clear">
  353. <footer>
  354. Documentation generated by <a href="https://github.com/jsdoc3/jsdoc">JSDoc 3.5.5</a> on Wed Oct 03 2018 15:59:34 GMT+0200 (W. Europe Daylight Time)
  355. </footer>
  356. <script> prettyPrint(); </script>
  357. <script src="scripts/linenumber.js"> </script>
  358. </body>
  359. </html>