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

Commit

Permalink
feat(nodes.js): add nodes class and proxy node's find method
Browse files Browse the repository at this point in the history
  • Loading branch information
stfsy committed Dec 25, 2016
1 parent 1850902 commit 948998f
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 0 deletions.
2 changes: 2 additions & 0 deletions lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

const Document = require('./document')
const Node = require('./node')
const Nodes = require('./nodes')
const Attribute = require('./attribute')
const Text = require('./text')

Expand All @@ -12,5 +13,6 @@ module.exports = {
Document: Document,
Attr: Attribute,
Node: Node,
Nodes: Nodes,
Text: Text
}
60 changes: 60 additions & 0 deletions lib/nodes.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
'use strict'

/**
* @class
* @memberof node-html-light
*/
class Nodes {

/**
* Wrap a set of Nodes to get access to utility functions
* @param {Array<Node>} elems an array of nodes
* @returns {Node} a new Node
*/
static fromArray(elems) {
return new Nodes(elems)
}

/**
* @constructor
* @private
* @description <b>Do not use this method directly. Use one of the static helper methods instead.</b>
* @param {Array<Node>} elems an array of nodes
* @returns {Nodes} a new object wrapping the given array of nodes
*/
constructor(elems) {
this._elements = elems
}

/**
* Returns an array of nodes matching tag name and attributes
* @param {Object} element an object whos properties reflect the properties of the element we are looking for
* @param {Array<Attribute>} [attrs=empty] attrs an array of attributes
* @param {Number} [limit=Infinity] limit the max number of results
* @returns {Array<Node>}
*/
find(element, attrs, limit) {
let result = []

if (limit === undefined || limit === null) {
limit = Infinity
}

for (let i = 0, n = this._elements.length; i < n; i++) {
const el = this._elements[i]
const foundElements = el.find(element, attrs, limit)
result = result.concat(foundElements)
const size = foundElements.length

if (size >= limit) {
break
} else {
limit = limit - size
}
}

return result
}
}

module.exports = Nodes

0 comments on commit 948998f

Please sign in to comment.