From 881d708e72383908753af57417910a2a7a339711 Mon Sep 17 00:00:00 2001 From: taoqf Date: Sun, 26 Jan 2020 21:57:27 +0800 Subject: [PATCH] remove duplicated items in querySelectAll --- src/index.ts | 15 ++++++++------- test/html.js | 12 +++++++++++- 2 files changed, 19 insertions(+), 8 deletions(-) diff --git a/src/index.ts b/src/index.ts index 1ff2245..7b52360 100755 --- a/src/index.ts +++ b/src/index.ts @@ -219,7 +219,7 @@ export class HTMLElement extends Node { currentBlock.push(text); } } - } + } dfs(this); return blocks .map(function (block) { @@ -353,11 +353,12 @@ export class HTMLElement extends Node { } else { if (selector.includes(',')) { const selectors = selector.split(',') as string[]; - let result = [] as HTMLElement[]; - selectors.forEach((s) => { - result = result.concat(this.querySelectorAll(s.trim())); - }); - return result; + return Array.from(selectors.reduce((pre, cur) => { + const result = this.querySelectorAll(cur.trim()) as HTMLElement[]; + return result.reduce((p, c) => { + return p.add(c); + }, pre); + }, new Set())); } matcher = new Matcher(selector); } @@ -801,7 +802,7 @@ export function parse(data: string, options?: { // this is a comment if (options.comment) { // Only keep what is in between - const text = data.substring(lastTextPos - 3 , lastTextPos - match[0].length + 4); + const text = data.substring(lastTextPos - 3, lastTextPos - match[0].length + 4); currentParent.appendChild(new CommentNode(text)); } continue; diff --git a/test/html.js b/test/html.js index d50e7b9..aed01ad 100644 --- a/test/html.js +++ b/test/html.js @@ -129,7 +129,7 @@ describe('HTML Parser', function () { it('should parse picture element', function () { var root = parseHTML('Example'); - + var picture = new HTMLElement('picture', {}, ''); var source = picture.appendChild(new HTMLElement('source', {}, 'srcset="/images/example-1.jpg 1200w, /images/example-2.jpg 1600w" sizes="100vw"')); var img = picture.appendChild(new HTMLElement('img', {}, 'src="/images/example.jpg" alt="Example"')); @@ -341,6 +341,16 @@ describe('HTML Parser', function () { root.querySelectorAll('#id span').should.eql(root.firstChild.firstChild.childNodes); root.querySelectorAll('#id, #id .b').should.eql([root.firstChild, root.firstChild.firstChild.firstChild]); }); + it('should return just one element', function () { + var root = parseHTML('