propertyName.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. // module code
  52. "await",
  53. // skip future reserved keywords defined under ES1 till ES3
  54. // additional
  55. "null",
  56. "true",
  57. "false"
  58. ]);
  59. /**
  60. * @summary Returns a valid JS property name for the given property.
  61. * Certain strings like "default", "null", and names with whitespace are not
  62. * valid JS property names, so they are returned as strings.
  63. * @param {string} prop property name to analyze
  64. * @returns {string} valid JS property name
  65. */
  66. const propertyName = prop => {
  67. if (SAFE_IDENTIFIER.test(prop) && !RESERVED_IDENTIFIER.has(prop)) {
  68. return prop;
  69. }
  70. return JSON.stringify(prop);
  71. };
  72. module.exports = { SAFE_IDENTIFIER, RESERVED_IDENTIFIER, propertyName };