propertyAccess.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const SAFE_IDENTIFIER = /^[_a-zA-Z$][_a-zA-Z$0-9]*$/;
  7. const RESERVED_IDENTIFIER = new Set([
  8. "break",
  9. "case",
  10. "catch",
  11. "class",
  12. "const",
  13. "continue",
  14. "debugger",
  15. "default",
  16. "delete",
  17. "do",
  18. "else",
  19. "export",
  20. "extends",
  21. "finally",
  22. "for",
  23. "function",
  24. "if",
  25. "import",
  26. "in",
  27. "instanceof",
  28. "new",
  29. "return",
  30. "super",
  31. "switch",
  32. "this",
  33. "throw",
  34. "try",
  35. "typeof",
  36. "var",
  37. "void",
  38. "while",
  39. "with",
  40. "enum",
  41. // strict mode
  42. "implements",
  43. "interface",
  44. "let",
  45. "package",
  46. "private",
  47. "protected",
  48. "public",
  49. "static",
  50. "yield",
  51. "yield",
  52. // module code
  53. "await",
  54. // skip future reserved keywords defined under ES1 till ES3
  55. // additional
  56. "null",
  57. "true",
  58. "false"
  59. ]);
  60. const propertyAccess = (properties, start = 0) => {
  61. let str = "";
  62. for (let i = start; i < properties.length; i++) {
  63. const p = properties[i];
  64. if (`${+p}` === p) {
  65. str += `[${p}]`;
  66. } else if (SAFE_IDENTIFIER.test(p) && !RESERVED_IDENTIFIER.has(p)) {
  67. str += `.${p}`;
  68. } else {
  69. str += `[${JSON.stringify(p)}]`;
  70. }
  71. }
  72. return str;
  73. };
  74. module.exports = propertyAccess;