UTF16Encoding.js 700 B

12345678910111213141516171819202122232425
  1. 'use strict';
  2. var GetIntrinsic = require('get-intrinsic');
  3. var $TypeError = GetIntrinsic('%TypeError%');
  4. var $fromCharCode = GetIntrinsic('%String.fromCharCode%');
  5. var floor = require('./floor');
  6. var modulo = require('./modulo');
  7. var isCodePoint = require('../helpers/isCodePoint');
  8. // https://262.ecma-international.org/7.0/#sec-utf16encoding
  9. module.exports = function UTF16Encoding(cp) {
  10. if (!isCodePoint(cp)) {
  11. throw new $TypeError('Assertion failed: `cp` must be >= 0 and <= 0x10FFFF');
  12. }
  13. if (cp <= 65535) {
  14. return $fromCharCode(cp);
  15. }
  16. var cu1 = floor((cp - 65536) / 1024) + 0xD800;
  17. var cu2 = modulo(cp - 65536, 1024) + 0xDC00;
  18. return $fromCharCode(cu1) + $fromCharCode(cu2);
  19. };