Skip to content

Commit

Permalink
Add Node.contains() method that returns a boolean value indicating wh…
Browse files Browse the repository at this point in the history
…ether a node is a descendant of a given node or not (closes #2).
  • Loading branch information
cheton committed Nov 28, 2016
1 parent b8939c5 commit ce844f3
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
12 changes: 12 additions & 0 deletions src/node.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,18 @@ class Node {

this.children = this.children || [];
}
// Returns a boolean value indicating whether a node is a descendant of a given node or not.
// @param {object} node Specifies the node that may be contained by (a descendant of) a specified node.
// @return {boolean} Returns true if a node is a descendant of a specified node, otherwise false. A descendant can be a child, grandchild, great-grandchild, and so on.
contains(node) {
while ((node instanceof Node) && (node !== this)) {
if (node.parent === this) {
return true;
}
node = node.parent;
}
return false;
}
// Gets a child node at the specified index.
// @param {number} The index of the child node.
// @return {object} Returns an object that defines the node, null otherwise.
Expand Down
18 changes: 17 additions & 1 deletion test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -565,12 +565,28 @@ test('[flatten] Ensure the parent node is an instance of Node after calling flat
t.end();
});

test('[node] getChildren/getParent/getFirstChild/getPreviousSibling/getNextSibling', (t) => {
test('[node] Node API', (t) => {
const tree = JSON.parse(fixtures.tree);
const nodes = flatten(tree, { openAllNodes: true });
const root = _.find(nodes, node => node.id === '<root>');
const alpha = _.find(nodes, node => node.id === 'alpha');
const bravo = _.find(nodes, node => node.id === 'bravo');
const juliet = _.find(nodes, node => node.id === 'juliet');

// contains
t.equal(root.contains(null), false);
t.equal(root.contains(undefined), false);
t.equal(root.contains({}), false);
t.equal(root.contains([]), false);
t.equal(root.contains(root), false);
t.equal(root.contains(alpha), true);
t.equal(root.contains(bravo), true);
t.equal(root.contains(juliet), true);
t.equal(alpha.contains(bravo), false);
t.equal(alpha.contains(juliet), false);
t.equal(bravo.contains(alpha), false);
t.equal(bravo.contains(juliet), true);
t.equal(juliet.contains(root), false);

// hasChildren
t.same(root.hasChildren(), true);
Expand Down

0 comments on commit ce844f3

Please sign in to comment.