fromcodepoint.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. /*! https://mths.be/fromcodepoint v0.2.1 by @mathias */
  2. if (!String.fromCodePoint) {
  3. (function() {
  4. var defineProperty = (function() {
  5. // IE 8 only supports `Object.defineProperty` on DOM elements
  6. var result;
  7. try {
  8. var object = {};
  9. var $defineProperty = Object.defineProperty;
  10. result = $defineProperty(object, "foo", object) && $defineProperty;
  11. } catch(error) {}
  12. return result;
  13. }());
  14. var stringFromCharCode = String.fromCharCode;
  15. var floor = Math.floor;
  16. var fromCodePoint = function(_) {
  17. var MAX_SIZE = 0x4000;
  18. var codeUnits = [];
  19. var highSurrogate;
  20. var lowSurrogate;
  21. var index = -1;
  22. var length = arguments.length;
  23. if (!length) {
  24. return "";
  25. }
  26. var result = "";
  27. while (++index < length) {
  28. var codePoint = Number(arguments[index]);
  29. if (
  30. !isFinite(codePoint) || // `NaN`, `+Infinity`, or `-Infinity`
  31. codePoint < 0 || // not a valid Unicode code point
  32. codePoint > 0x10FFFF || // not a valid Unicode code point
  33. floor(codePoint) != codePoint // not an integer
  34. ) {
  35. throw RangeError("Invalid code point: " + codePoint);
  36. }
  37. if (codePoint <= 0xFFFF) { // BMP code point
  38. codeUnits.push(codePoint);
  39. } else { // Astral code point; split in surrogate halves
  40. // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
  41. codePoint -= 0x10000;
  42. highSurrogate = (codePoint >> 10) + 0xD800;
  43. lowSurrogate = (codePoint % 0x400) + 0xDC00;
  44. codeUnits.push(highSurrogate, lowSurrogate);
  45. }
  46. if (index + 1 == length || codeUnits.length > MAX_SIZE) {
  47. result += stringFromCharCode.apply(null, codeUnits);
  48. codeUnits.length = 0;
  49. }
  50. }
  51. return result;
  52. };
  53. if (defineProperty) {
  54. defineProperty(String, "fromCodePoint", {
  55. "value": fromCodePoint,
  56. "configurable": true,
  57. "writable": true
  58. });
  59. } else {
  60. String.fromCodePoint = fromCodePoint;
  61. }
  62. }());
  63. }