propertyAccess.js 728 B

123456789101112131415161718192021222324252627282930313233
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const {
  7. SAFE_IDENTIFIER,
  8. RESERVED_IDENTIFIER
  9. } = require("../util/propertyName");
  10. /**
  11. * @param {ArrayLike<string>} properties properties
  12. * @param {number} start start index
  13. * @returns {string} chain of property accesses
  14. */
  15. const propertyAccess = (properties, start = 0) => {
  16. let str = "";
  17. for (let i = start; i < properties.length; i++) {
  18. const p = properties[i];
  19. if (`${+p}` === p) {
  20. str += `[${p}]`;
  21. } else if (SAFE_IDENTIFIER.test(p) && !RESERVED_IDENTIFIER.has(p)) {
  22. str += `.${p}`;
  23. } else {
  24. str += `[${JSON.stringify(p)}]`;
  25. }
  26. }
  27. return str;
  28. };
  29. module.exports = propertyAccess;