aboutsummaryrefslogtreecommitdiff
path: root/js/lib/from-code-point.js
blob: 94eca655faf8138d318c1041f3f202d74944399e (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 = String.fromCodePoint;
  5. } else {
  6. var stringFromCharCode = String.fromCharCode;
  7. var floor = Math.floor;
  8. var fromCodePoint = function(_) {
  9. var MAX_SIZE = 0x4000;
  10. var codeUnits = [];
  11. var highSurrogate;
  12. var lowSurrogate;
  13. var index = -1;
  14. var length = arguments.length;
  15. if (!length) {
  16. return '';
  17. }
  18. var result = '';
  19. while (++index < length) {
  20. var codePoint = Number(arguments[index]);
  21. if (
  22. !isFinite(codePoint) || // `NaN`, `+Infinity`, or `-Infinity`
  23. codePoint < 0 || // not a valid Unicode code point
  24. codePoint > 0x10FFFF || // not a valid Unicode code point
  25. floor(codePoint) != codePoint // not an integer
  26. ) {
  27. return String.fromCharCode(0xFFFD);
  28. }
  29. if (codePoint <= 0xFFFF) { // BMP code point
  30. codeUnits.push(codePoint);
  31. } else { // Astral code point; split in surrogate halves
  32. // http://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
  33. codePoint -= 0x10000;
  34. highSurrogate = (codePoint >> 10) + 0xD800;
  35. lowSurrogate = (codePoint % 0x400) + 0xDC00;
  36. codeUnits.push(highSurrogate, lowSurrogate);
  37. }
  38. if (index + 1 == length || codeUnits.length > MAX_SIZE) {
  39. result += stringFromCharCode.apply(null, codeUnits);
  40. codeUnits.length = 0;
  41. }
  42. }
  43. return result;
  44. };
  45. module.exports = fromCodePoint;
  46. }