stringToPath.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. // @ts-nocheck
  2. import memoizeCapped from "./memoizeCapped.js";
  3. const charCodeOfDot = ".".charCodeAt(0);
  4. const reEscapeChar = /\\(\\)?/g;
  5. const rePropName = RegExp(
  6. // Match anything that isn't a dot or bracket.
  7. "[^.[\\]]+" +
  8. "|" +
  9. // Or match property names within brackets.
  10. "\\[(?:" +
  11. // Match a non-string expression.
  12. "([^\"'][^[]*)" +
  13. "|" +
  14. // Or match strings (supports escaping characters).
  15. "([\"'])((?:(?!\\2)[^\\\\]|\\\\.)*?)\\2" +
  16. ")\\]" +
  17. "|" +
  18. // Or match "" as the space between consecutive dots or empty brackets.
  19. "(?=(?:\\.|\\[\\])(?:\\.|\\[\\]|$))", "g");
  20. /**
  21. * Converts `string` to a property path array.
  22. *
  23. * @private
  24. * @param {string} string The string to convert.
  25. * @returns {Array} Returns the property path array.
  26. */
  27. const stringToPath = memoizeCapped((string) => {
  28. const result = [];
  29. if (string.charCodeAt(0) === charCodeOfDot) {
  30. result.push("");
  31. }
  32. string.replace(rePropName, (match, expression, quote, subString) => {
  33. let key = match;
  34. if (quote) {
  35. key = subString.replace(reEscapeChar, "$1");
  36. }
  37. else if (expression) {
  38. key = expression.trim();
  39. }
  40. result.push(key);
  41. });
  42. return result;
  43. });
  44. export default stringToPath;