UNPKG

awesome-string

Version:

The ultimate JavaScript string library

44 lines (43 loc) 1.92 kB
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 * as.codePointAt('rain', 1); * // => 97, or 0x0061 * * as.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; }