|
1 | 1 | /*! http://mths.be/codepointat v0.1.0 by @mathias */
|
2 | 2 | if (!String.prototype.codePointAt) {
|
3 |
| - String.prototype.codePointAt = function(position) { |
4 |
| - 'use strict'; |
5 |
| - if (this == null) { |
6 |
| - throw TypeError(); |
7 |
| - } |
8 |
| - var string = String(this); |
9 |
| - var size = string.length; |
10 |
| - // `ToInteger` |
11 |
| - var index = position ? Number(position) : 0; |
12 |
| - if (index != index) { // better `isNaN` |
13 |
| - index = 0; |
14 |
| - } |
15 |
| - // Account for out-of-bounds indices: |
16 |
| - if (index < 0 || index >= size) { |
17 |
| - return undefined; |
18 |
| - } |
19 |
| - // Get the first code unit |
20 |
| - var first = string.charCodeAt(index); |
21 |
| - var second; |
22 |
| - if ( // check if it’s the start of a surrogate pair |
23 |
| - first >= 0xD800 && first <= 0xDBFF && // high surrogate |
24 |
| - size > index + 1 // there is a next code unit |
25 |
| - ) { |
26 |
| - second = string.charCodeAt(index + 1); |
27 |
| - if (second >= 0xDC00 && second <= 0xDFFF) { // low surrogate |
28 |
| - // http://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae |
29 |
| - return (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000; |
| 3 | + (function() { |
| 4 | + 'use strict'; // needed to support `apply`/`call` with `undefined`/`null` |
| 5 | + var codePointAt = function(position) { |
| 6 | + if (this == null) { |
| 7 | + throw TypeError(); |
| 8 | + } |
| 9 | + var string = String(this); |
| 10 | + var size = string.length; |
| 11 | + // `ToInteger` |
| 12 | + var index = position ? Number(position) : 0; |
| 13 | + if (index != index) { // better `isNaN` |
| 14 | + index = 0; |
| 15 | + } |
| 16 | + // Account for out-of-bounds indices: |
| 17 | + if (index < 0 || index >= size) { |
| 18 | + return undefined; |
| 19 | + } |
| 20 | + // Get the first code unit |
| 21 | + var first = string.charCodeAt(index); |
| 22 | + var second; |
| 23 | + if ( // check if it’s the start of a surrogate pair |
| 24 | + first >= 0xD800 && first <= 0xDBFF && // high surrogate |
| 25 | + size > index + 1 // there is a next code unit |
| 26 | + ) { |
| 27 | + second = string.charCodeAt(index + 1); |
| 28 | + if (second >= 0xDC00 && second <= 0xDFFF) { // low surrogate |
| 29 | + // http://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae |
| 30 | + return (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000; |
| 31 | + } |
30 | 32 | }
|
| 33 | + return first; |
| 34 | + }; |
| 35 | + if (Object.defineProperty) { |
| 36 | + Object.defineProperty(String.prototype, 'codePointAt', { |
| 37 | + 'value': codePointAt, |
| 38 | + 'configurable': true, |
| 39 | + 'writable': true |
| 40 | + }); |
| 41 | + } else { |
| 42 | + String.prototype.codePointAt = codePointAt; |
31 | 43 | }
|
32 |
| - return first; |
33 |
| - }; |
| 44 | + }()); |
34 | 45 | }
|
0 commit comments