From b3010d7ee7585c996c3d2ee176e45d376f9daae9 Mon Sep 17 00:00:00 2001 From: 5saviahv <49443574+5saviahv@users.noreply.github.com> Date: Tue, 26 Jan 2021 22:23:34 +0200 Subject: [PATCH] fix: Add length instance property to all Cheerio instances (#1681) --- lib/cheerio.js | 2 +- lib/static.js | 8 +++++--- test/api/deprecated.js | 7 +++++++ 3 files changed, 13 insertions(+), 4 deletions(-) diff --git a/lib/cheerio.js b/lib/cheerio.js index b03942367a..46a706cfcb 100644 --- a/lib/cheerio.js +++ b/lib/cheerio.js @@ -40,6 +40,7 @@ var Cheerio = (module.exports = function (selector, context, root, options) { return new Cheerio(selector, context, root, options); } + this.length = 0; this.options = Object.assign( {}, defaultOptions, @@ -106,7 +107,6 @@ Cheerio.prototype.cheerio = '[cheerio object]'; /* * Make cheerio an array-like object */ -Cheerio.prototype.length = 0; Cheerio.prototype.splice = Array.prototype.splice; /** diff --git a/lib/static.js b/lib/static.js index fb3fe10726..188235a9ef 100644 --- a/lib/static.js +++ b/lib/static.js @@ -202,9 +202,11 @@ exports.merge = function (arr1, arr2) { if (!isArrayLike(arr1) || !isArrayLike(arr2)) { return; } - var newLength = arr1.length + arr2.length; - for (var i = 0; i < arr2.length; i++) { - arr1[i + arr1.length] = arr2[i]; + var newLength = arr1.length; + var len = +arr2.length; + + for (var i = 0; i < len; i++) { + arr1[newLength++] = arr2[i]; } arr1.length = newLength; return arr1; diff --git a/test/api/deprecated.js b/test/api/deprecated.js index ddf0c02273..3f44950cd8 100644 --- a/test/api/deprecated.js +++ b/test/api/deprecated.js @@ -49,6 +49,13 @@ describe('deprecated APIs', function () { expect(typeof cheerio.merge).toBe('function'); }); + // #1674 - merge, wont accept Cheerio object + it('should be a able merge array and cheerio object', function () { + var ret = cheerio.merge(new cheerio(), ['elem1', 'elem2']); + expect(typeof ret).toBe('object'); + expect(ret).toHaveLength(2); + }); + it('(arraylike, arraylike) : should return an array', function () { var ret = cheerio.merge(arr1, arr2); expect(typeof ret).toBe('object');