Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

node.contains(...) #2

Closed
mudcube opened this issue Nov 26, 2016 · 3 comments
Closed

node.contains(...) #2

mudcube opened this issue Nov 26, 2016 · 3 comments

Comments

@mudcube
Copy link
Contributor

mudcube commented Nov 26, 2016

What do you think about having a node.contains(...) method? This would be very helpful, as currently it's possible to create an infinite loop when adding nodes as a sub-node to itself in InfiniteTree.

contains(target) {
	const children = this.children
	const length = children.length
	for (let i = 0; i < length; i++) {
		const node = children[i]
		if (node === target) return true
		if (node.children) {
			const result = node.contains(target)
			if (result) return result
		}
	}
}
@cheton
Copy link
Owner

cheton commented Nov 26, 2016

It's fine with me to add a node.contains() method. From your example, traversing up through its ancestors should be more efficient since the target node has a parent link:

contains(target) {
    while (target && target !== this) {
        if (target.parent === this) {
            return true;
        }
        target = target.parent;
    }

    return false;
}

@mudcube
Copy link
Contributor Author

mudcube commented Nov 27, 2016

Good point! That's much more efficient.

@cheton cheton closed this as completed in ce844f3 Nov 28, 2016
@cheton
Copy link
Owner

cheton commented Nov 28, 2016

It's now included in 0.10.0. Thank you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants