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