-
Notifications
You must be signed in to change notification settings - Fork 136
Expand file tree
/
Copy pathcode_point_at.js
More file actions
44 lines (43 loc) · 1.87 KB
/
code_point_at.js
File metadata and controls
44 lines (43 loc) · 1.87 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import { getAstralNumberFromSurrogatePair, isHighSurrogate, isLowSurrogate } from 'helper/string/surrogate_pair';
import coerceToNumber from 'helper/number/coerce_to_number';
import coerceToString from 'helper/string/coerce_to_string';
import nanDefault from 'helper/number/nan_default';
/**
* Get the Unicode code point value of the character at `position`. <br/>
* If a valid UTF-16 <a href="https://rainsoft.io/what-every-javascript-developer-should-know-about-unicode/#24surrogatepairs">
* surrogate pair</a> starts at `position`, the
* <a href="https://rainsoft.io/what-every-javascript-developer-should-know-about-unicode/#astralplanes">astral code point</a>
* value at `position` is returned.
*
* @function codePointAt
* @static
* @since 1.0.0
* @memberOf Chop
* @param {string} [subject=''] The string to extract from.
* @param {number} position The position to get the code point number.
* @return {number} Returns a non-negative number less than or equal to `0x10FFFF`.
* @example
* v.codePointAt('rain', 1);
* // => 97, or 0x0061
*
* v.codePointAt('\uD83D\uDE00 is smile', 0); // or '😀 is smile'
* // => 128512, or 0x1F600
*/
export default function codePointAt(subject, position) {
const subjectString = coerceToString(subject);
const subjectStringLength = subjectString.length;
let positionNumber = coerceToNumber(position);
positionNumber = nanDefault(positionNumber, 0);
if (positionNumber < 0 || positionNumber >= subjectStringLength) {
return undefined;
}
const firstCodePoint = subjectString.charCodeAt(positionNumber);
let secondCodePoint;
if (isHighSurrogate(firstCodePoint) && subjectStringLength > positionNumber + 1) {
secondCodePoint = subjectString.charCodeAt(positionNumber + 1);
if (isLowSurrogate(secondCodePoint)) {
return getAstralNumberFromSurrogatePair(firstCodePoint, secondCodePoint);
}
}
return firstCodePoint;
}