extract.js 1.4 KB

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