extract.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.extract = extract;
  4. function getExtractDescr(descr) {
  5. var _a;
  6. if (typeof descr === 'string') {
  7. return { selector: descr, value: 'textContent' };
  8. }
  9. return {
  10. selector: descr.selector,
  11. value: (_a = descr.value) !== null && _a !== void 0 ? _a : 'textContent',
  12. };
  13. }
  14. /**
  15. * Extract multiple values from a document, and store them in an object.
  16. *
  17. * @param map - An object containing key-value pairs. The keys are the names of
  18. * the properties to be created on the object, and the values are the
  19. * selectors to be used to extract the values.
  20. * @returns An object containing the extracted values.
  21. */
  22. function extract(map) {
  23. const ret = {};
  24. for (const key in map) {
  25. const descr = map[key];
  26. const isArray = Array.isArray(descr);
  27. const { selector, value } = getExtractDescr(isArray ? descr[0] : descr);
  28. const fn = typeof value === 'function'
  29. ? value
  30. : typeof value === 'string'
  31. ? (el) => this._make(el).prop(value)
  32. : (el) => this._make(el).extract(value);
  33. if (isArray) {
  34. ret[key] = this._findBySelector(selector, Number.POSITIVE_INFINITY)
  35. .map((_, el) => fn(el, key, ret))
  36. .get();
  37. }
  38. else {
  39. const $ = this._findBySelector(selector, 1);
  40. ret[key] = $.length > 0 ? fn($[0], key, ret) : undefined;
  41. }
  42. }
  43. return ret;
  44. }
  45. //# sourceMappingURL=extract.js.map