stringToParts.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. 'use strict';
  2. module.exports = function stringToParts(str) {
  3. const result = [];
  4. let curPropertyName = '';
  5. let state = 'DEFAULT';
  6. for (let i = 0; i < str.length; ++i) {
  7. // Fall back to treating as property name rather than bracket notation if
  8. // square brackets contains something other than a number.
  9. if (state === 'IN_SQUARE_BRACKETS' && !/\d/.test(str[i]) && str[i] !== ']') {
  10. state = 'DEFAULT';
  11. curPropertyName = result[result.length - 1] + '[' + curPropertyName;
  12. result.splice(result.length - 1, 1);
  13. }
  14. if (str[i] === '[') {
  15. if (state !== 'IMMEDIATELY_AFTER_SQUARE_BRACKETS') {
  16. result.push(curPropertyName);
  17. curPropertyName = '';
  18. }
  19. state = 'IN_SQUARE_BRACKETS';
  20. } else if (str[i] === ']') {
  21. if (state === 'IN_SQUARE_BRACKETS') {
  22. state = 'IMMEDIATELY_AFTER_SQUARE_BRACKETS';
  23. result.push(curPropertyName);
  24. curPropertyName = '';
  25. } else {
  26. state = 'DEFAULT';
  27. curPropertyName += str[i];
  28. }
  29. } else if (str[i] === '.') {
  30. if (state !== 'IMMEDIATELY_AFTER_SQUARE_BRACKETS') {
  31. result.push(curPropertyName);
  32. curPropertyName = '';
  33. }
  34. state = 'DEFAULT';
  35. } else {
  36. curPropertyName += str[i];
  37. }
  38. }
  39. if (state !== 'IMMEDIATELY_AFTER_SQUARE_BRACKETS') {
  40. result.push(curPropertyName);
  41. }
  42. return result;
  43. };