propertyName.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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. /**
  61. * @summary Returns a valid JS property name for the given property.
  62. * Certain strings like "default", "null", and names with whitespace are not
  63. * valid JS property names, so they are returned as strings.
  64. *
  65. * @param {string} prop property name to analyze
  66. * @returns {string} valid JS property name
  67. */
  68. const propertyName = prop => {
  69. if (SAFE_IDENTIFIER.test(prop) && !RESERVED_IDENTIFIER.has(prop)) {
  70. return prop;
  71. } else {
  72. return JSON.stringify(prop);
  73. }
  74. };
  75. module.exports = { SAFE_IDENTIFIER, RESERVED_IDENTIFIER, propertyName };