propertyName.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. * @param {string} prop property name to analyze
  65. * @returns {string} valid JS property name
  66. */
  67. const propertyName = prop => {
  68. if (SAFE_IDENTIFIER.test(prop) && !RESERVED_IDENTIFIER.has(prop)) {
  69. return prop;
  70. }
  71. return JSON.stringify(prop);
  72. };
  73. module.exports = { SAFE_IDENTIFIER, RESERVED_IDENTIFIER, propertyName };