Improve Item#isDescendant(item) and introduce Item#isAncestor(item).

This commit is contained in:
Jonathan Puckey 2011-02-12 16:41:57 +01:00
parent e9e987f304
commit 38ada4abc1
2 changed files with 33 additions and 7 deletions

View file

@ -290,14 +290,37 @@ Item = Base.extend({
* @return {@true if it is inside the specified item}
*/
isDescendant: function(item) {
var parent = this, isDescendant = false;
var parent = this;
while(parent) {
if(parent == item) {
isDescendant = true;
break;
}
if(parent == item)
return true;
parent = parent.parent;
}
return isDescendant;
return false;
},
/**
* Checks if the item is an ancestor of the specified item.
*
* Sample code:
* <code>
* var group = new Group();
* var path = new Path();
* group.appendChild(path);
* print(group.isAncestor(path)); // true
* print(path.isAncestor(group)); // false
* </code>
*
* @param item the item to check against
* @return {@true if the item is an ancestor of the specified item}
*/
isAncestor: function(item) {
var parent = item;
while(parent) {
if(parent == this)
return true;
parent = parent.parent;
}
return false;
}
});

View file

@ -53,11 +53,14 @@ test('moveBelow(item)', function() {
equals(secondPath.index < firstPath.index, true);
});
test('isDescendant(item)', function() {
test('isDescendant(item) / isAncestor(item)', function() {
var doc = new Doc();
var path = new Path();
equals(path.isDescendant(doc.activeLayer), true);
equals(doc.activeLayer.isDescendant(path), false);
equals(path.isAncestor(doc.activeLayer), false);
equals(doc.activeLayer.isAncestor(path), true);
});
test('getPreviousSibling() / getNextSibling()', function() {