Skip to content
This repository has been archived by the owner on Jan 6, 2025. It is now read-only.

Commit

Permalink
feat: add filter by type function
Browse files Browse the repository at this point in the history
  • Loading branch information
stfsy committed Jul 6, 2021
1 parent c2a14ab commit c3e11a8
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 1 deletion.
17 changes: 16 additions & 1 deletion lib/node.js
Original file line number Diff line number Diff line change
Expand Up @@ -253,14 +253,29 @@ class Node {

/**
* Search a node and its children for nodes passing a test function.
* @param {Node} node the root node
* @param {Function} callback the callback returns true for elements that should be in the returned array
* @param {Number} [limit=Infinity] limit the max number of results
* @returns {Array<Node>}
*/
filter(callback, limit = Infinity) {
return domUtils.filter(callback, this._element, true, limit).map(el => Node.of(el))
}

/**
* Search a node and its children by type for nodes passing a test function.
* @param {Function} callback the callback returns true for elements that should be in the returned array
* @param {Array<String>} types for these types the callback will be fired @see i.e. Node.TYPE_TAG
* @param {Number} [limit=Infinity] limit the max number of results
* @returns {Array<Node>}
*/
filterByType(callback, types, limit = Infinity) {
return this.filter((node) => {
if (types.includes(node.type)) {
callback(node)
}
}, limit)
}

/**
* Removes a child node
* @param {Node|Array<Node>} child the child node to remove
Expand Down
34 changes: 34 additions & 0 deletions test/spec/node.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,40 @@ describe('Node', () => {
expect(count).to.be.equal(5)
})

it('should callback for each node and childnodes by type tag', () => {
const node = Node.fromString(['<head>',
'<meta content="" name="description">',
'<style></style>',
'<script></script>',
'<meta content="width=device-width,user-scalable=no" name="viewport">',
'<meta content="#795548" name="theme-color">',
'<title></title>',
'</head>'].join(''))

let count = 0
node.filterByType((el) => {
count += 1
}, [Node.TYPE_TAG])
expect(count).to.be.equal(5)
})

it('should callback for each node and childnodes by type style and script', () => {
const node = Node.fromString(['<head>',
'<meta content="" name="description">',
'<style></style>',
'<script></script>',
'<meta content="width=device-width,user-scalable=no" name="viewport">',
'<meta content="#795548" name="theme-color">',
'<title></title>',
'</head>'].join(''))

let count = 0
node.filterByType((el) => {
count += 1
}, [Node.TYPE_STYLE, Node.TYPE_SCRIPT])
expect(count).to.be.equal(2)
})

it('returns children when callback returned true', () => {
const node = Node.fromString(['<head>',
'<meta content="" name="description">',
Expand Down

0 comments on commit c3e11a8

Please sign in to comment.