parse-path.js 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. var reFirstKey = /^[^\[]*/
  2. var reDigitPath = /^\[(\d+)\]/
  3. var reNormalPath = /^\[([^\]]+)\]/
  4. function parsePath (key) {
  5. function failure () {
  6. return [{ type: 'object', key: key, last: true }]
  7. }
  8. var firstKey = reFirstKey.exec(key)[0]
  9. if (!firstKey) return failure()
  10. var len = key.length
  11. var pos = firstKey.length
  12. var tail = { type: 'object', key: firstKey }
  13. var steps = [tail]
  14. while (pos < len) {
  15. var m
  16. if (key[pos] === '[' && key[pos + 1] === ']') {
  17. pos += 2
  18. tail.append = true
  19. if (pos !== len) return failure()
  20. continue
  21. }
  22. m = reDigitPath.exec(key.substring(pos))
  23. if (m !== null) {
  24. pos += m[0].length
  25. tail.nextType = 'array'
  26. tail = { type: 'array', key: parseInt(m[1], 10) }
  27. steps.push(tail)
  28. continue
  29. }
  30. m = reNormalPath.exec(key.substring(pos))
  31. if (m !== null) {
  32. pos += m[0].length
  33. tail.nextType = 'object'
  34. tail = { type: 'object', key: m[1] }
  35. steps.push(tail)
  36. continue
  37. }
  38. return failure()
  39. }
  40. tail.last = true
  41. return steps
  42. }
  43. module.exports = parsePath