fromcodepoint.js 1.9 KB

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