@divriots/cheerio
Version:
The fast, flexible & elegant library for parsing and manipulating HTML and XML.
51 lines • 1.78 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.extract = void 0;
function getExtractDescr(descr) {
var _a;
if (typeof descr === 'string') {
return { selector: descr, value: 'textContent' };
}
return {
selector: descr.selector,
value: (_a = descr.value) !== null && _a !== void 0 ? _a : 'textContent',
};
}
/**
* Extract multiple values from a document, and store them in an object.
*
* @param map - An object containing key-value pairs. The keys are the names of
* the properties to be created on the object, and the values are the
* selectors to be used to extract the values.
* @returns An object containing the extracted values.
*/
function extract(map) {
var _this = this;
var ret = {};
var _loop_1 = function (key) {
var descr = map[key];
var isArray = Array.isArray(descr);
var _a = getExtractDescr(isArray ? descr[0] : descr), selector = _a.selector, value = _a.value;
var fn = typeof value === 'function'
? value
: typeof value === 'string'
? function (el) { return _this._make(el).prop(value); }
: function (el) { return _this._make(el).extract(value); };
if (isArray) {
ret[key] = this_1._findBySelector(selector, Number.POSITIVE_INFINITY)
.map(function (_, el) { return fn(el, key, ret); })
.get();
}
else {
var $ = this_1._findBySelector(selector, 1);
ret[key] = $.length > 0 ? fn($[0], key, ret) : undefined;
}
};
var this_1 = this;
for (var key in map) {
_loop_1(key);
}
return ret;
}
exports.extract = extract;
//# sourceMappingURL=extract.js.map