diff --git a/src/node.js b/src/node.js index 1885ce9..9652bea 100644 --- a/src/node.js +++ b/src/node.js @@ -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. diff --git a/test/index.js b/test/index.js index 4dfb44d..b480be8 100644 --- a/test/index.js +++ b/test/index.js @@ -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 === ''); 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);