aboutsummaryrefslogtreecommitdiff
path: root/js/lib/from-code-point.js
blob: a0557b3a1e392585fbc2d0ddda44771d245c11e0 (plain)
  1. "use strict";
  2. // derived from https://github.com/mathiasbynens/String.fromCodePoint
  3. /*! http://mths.be/fromcodepoint v0.2.1 by @mathias */
  4. if (String.fromCodePoint) {
  5. module.exports = function (_) {
  6. try {
  7. return String.fromCodePoint(_);
  8. } catch (e) {
  9. if (e instanceof RangeError) {
  10. return String.fromCharCode(0xFFFD);
  11. }
  12. throw e;
  13. }
  14. };
  15. } else {
  16. var stringFromCharCode = String.fromCharCode;
  17. var floor = Math.floor;
  18. var fromCodePoint = function() {
  19. var MAX_SIZE = 0x4000;
  20. var codeUnits = [];
  21. var highSurrogate;
  22. var lowSurrogate;
  23. var index = -1;
  24. var length = arguments.length;
  25. if (!length) {
  26. return '';
  27. }
  28. var result = '';
  29. while (++index < length) {
  30. var codePoint = Number(arguments[index]);
  31. if (
  32. !isFinite(codePoint) || // `NaN`, `+Infinity`, or `-Infinity`
  33. codePoint < 0 || // not a valid Unicode code point
  34. codePoint > 0x10FFFF || // not a valid Unicode code point
  35. floor(codePoint) !== codePoint // not an integer
  36. ) {
  37. return String.fromCharCode(0xFFFD);
  38. }
  39. if (codePoint <= 0xFFFF) { // BMP code point
  40. codeUnits.push(codePoint);
  41. } else { // Astral code point; split in surrogate halves
  42. // http://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
  43. codePoint -= 0x10000;
  44. highSurrogate = (codePoint >> 10) + 0xD800;
  45. lowSurrogate = (codePoint % 0x400) + 0xDC00;
  46. codeUnits.push(highSurrogate, lowSurrogate);
  47. }
  48. if (index + 1 === length || codeUnits.length > MAX_SIZE) {
  49. result += stringFromCharCode.apply(null, codeUnits);
  50. codeUnits.length = 0;
  51. }
  52. }
  53. return result;
  54. };
  55. module.exports = fromCodePoint;
  56. }