main.js (2359B)
1 /** 2 * @license Apache-2.0 3 * 4 * Copyright (c) 2020 The Stdlib Authors. 5 * 6 * Licensed under the Apache License, Version 2.0 (the "License"); 7 * you may not use this file except in compliance with the License. 8 * You may obtain a copy of the License at 9 * 10 * http://www.apache.org/licenses/LICENSE-2.0 11 * 12 * Unless required by applicable law or agreed to in writing, software 13 * distributed under the License is distributed on an "AS IS" BASIS, 14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 * See the License for the specific language governing permissions and 16 * limitations under the License. 17 */ 18 19 'use strict'; 20 21 // MODULES // 22 23 var isString = require( './../../is-string' ).isPrimitive; 24 var isNonNegativeInteger = require( './../../is-nonnegative-integer' ).isPrimitive; 25 26 27 // VARIABLES // 28 29 // Range for a high surrogate 30 var OxD800 = 0xD800|0; // 55296 31 var OxDBFF = 0xDBFF|0; // 56319 32 33 // Range for a low surrogate 34 var OxDC00 = 0xDC00|0; // 56320 35 var OxDFFF = 0xDFFF|0; // 57343 36 37 38 // MAIN // 39 40 /** 41 * Tests if a position in a string marks the start of a UTF-16 surrogate pair. 42 * 43 * @private 44 * @param {string} str - input string 45 * @param {NonNegativeInteger} pos - position in string 46 * @throws {TypeError} first argument must be a string primitive 47 * @throws {TypeError} second argument must be a nonnegative integer 48 * @throws {RangeError} position must be a valid index in string 49 * @returns {boolean} boolean indicating whether the string has a surrogate pair at a position 50 * 51 * @example 52 * var out = hasUTF16SurrogatePairAt( '🌷', 0 ); 53 * // returns true 54 * 55 * @example 56 * var out = hasUTF16SurrogatePairAt( '🌷', 1 ); 57 * // returns false 58 */ 59 function hasUTF16SurrogatePairAt( str, pos ) { 60 var ch1; 61 var ch2; 62 if ( !isString( str ) ) { 63 throw new TypeError( 'invalid argument. Must provide a string. Value: `' + str + '`.' ); 64 } 65 if ( !isNonNegativeInteger( pos ) ) { 66 throw new TypeError( 'invalid argument. Must provide a valid position (nonnegative integer). Value: `' + pos + '`.' ); 67 } 68 if ( pos >= str.length ) { 69 throw new RangeError( 'invalid argument. Must provide a valid position (within string bounds). Value: `' + pos + '`.' ); 70 } 71 ch1 = str.charCodeAt( pos ); 72 ch2 = str.charCodeAt( pos + 1 ); 73 return ch1 >= OxD800 && ch1 <= OxDBFF && ch2 >= OxDC00 && ch2 <= OxDFFF; 74 } 75 76 77 // EXPORTS // 78 79 module.exports = hasUTF16SurrogatePairAt;