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