escape-unicode
Version:
Escapes Unicode characters
59 lines (52 loc) • 2.1 kB
JavaScript
/*
* Copyright (C) 2018 Alasdair Mercer
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
;
/**
* The available digits for hexadecimal values.
*
* @type {string[]}
*/
const hexDigits = '0123456789abcdef'.split('');
/**
* Parses the specified Unicode character found within the input string and calculate the hexadecimal representation of
* its Unicode code point.
*
* @param {string} ch - the character to be parsed to calculate the hexadecimal segment of the Unicode escape
* @return {string} The calculated Unicode code point in its hexadecimal representation.
*/
function parse(ch) {
const code = ch.codePointAt(0);
return toHexDigit((code >> 12) & 15) +
toHexDigit((code >> 8) & 15) +
toHexDigit((code >> 4) & 15) +
toHexDigit(code & 15);
}
/**
* Converts the specified <code>nibble</code> into a hexadecimal digit.
*
* @param {number} nibble - the nibble to be converted
* @return {string} The single-digit hexadecimal string.
*/
function toHexDigit(nibble) {
return hexDigits[nibble & 15];
}
module.exports = parse;