ObjectNavigator.js 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. class ObjectNavigator {
  2. constructor(raw = null) {
  3. if (Array.isArray(raw))
  4. this.raw = raw;
  5. else
  6. this.raw = [raw];
  7. }
  8. makeSelector(selector) {
  9. const result = [];
  10. selector = selector.trim();
  11. //последний индекс не учитывется, только если не задан явно
  12. if (selector && selector[selector.length - 1] == ']')
  13. selector += '/';
  14. const levels = selector.split('/');
  15. for (const level of levels) {
  16. const [name, indexPart] = level.split('[');
  17. let index = 0;
  18. if (indexPart) {
  19. const i = indexPart.indexOf(']');
  20. index = parseInt(indexPart.substring(0, i), 10) || 0;
  21. }
  22. result.push({name, index});
  23. }
  24. if (result.length);
  25. result[result.length - 1].last = true;
  26. return result;
  27. }
  28. select(selector = '') {
  29. selector = this.makeSelector(selector);
  30. let raw = this.raw;
  31. for (const s of selector) {
  32. if (s.name) {
  33. raw = raw[0];
  34. if (typeof(raw) === 'object' && !Array.isArray(raw))
  35. raw = raw[s.name];
  36. else
  37. raw = null;
  38. if (raw !== null && !s.last) {
  39. if (Array.isArray(raw))
  40. raw = raw[s.index];
  41. else if (s.index > 0)
  42. raw = null;
  43. }
  44. } else {
  45. raw = raw[s.index];
  46. }
  47. if (raw === undefined || raw === null) {
  48. raw = null;
  49. break;
  50. }
  51. if (!Array.isArray(raw))
  52. raw = [raw];
  53. }
  54. if (raw === null)
  55. return null;
  56. const result = [];
  57. for (const r of raw)
  58. result.push(new ObjectNavigator(r));
  59. return result;
  60. }
  61. $$(selector) {
  62. return this.select(selector);
  63. }
  64. $(selector) {
  65. const res = this.select(selector);
  66. return (res !== null && res.length ? res[0] : null);
  67. }
  68. get value() {
  69. return (this.raw.length ? this.raw[0] : null);
  70. }
  71. text(selector = '') {
  72. const res = this.$(`${selector}/*TEXT`);
  73. return (res ? res.value : null);
  74. }
  75. comment(selector = '') {
  76. const res = this.$(`${selector}/*COMMENT`);
  77. return (res ? res.value : null);
  78. }
  79. cdata(selector = '') {
  80. const res = this.$(`${selector}/*CDATA`);
  81. return (res ? res.value : null);
  82. }
  83. attrs(selector = '') {
  84. const res = this.$(`${selector}/*ATTRS`);
  85. return (res ? res.value : null);
  86. }
  87. }
  88. module.exports = ObjectNavigator;