ObjectInspector.js 2.6 KB

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