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

upgrade descendants and nodesBetween handlers to support aborting a graph scan #75

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

st3v0
Copy link

@st3v0 st3v0 commented Oct 25, 2022

Context

We need the ability to end the recursive scan (part way through the graph) which is performed by descendants and nodesBetween.

At the moment if we return false from the node handler; the scan continues to the next sibling in the graph. This is wasteful if there is a large amount of siblings and all we're trying to do is check if a node exists.

Proposed Solution

We could modify the nodesBetween node handler method to support more than returning boolean | void. If anything else is returned then the scan stops and returns that item.

This is a performance improvement solution with the added benefit of being able to use it for finding.

Checklist

Is this solution backwards compatible: ✅
Does this solution include tests: ❌

Examples

Say you want to get a text node from somewhere in the doc, which contains the text 'foobar', you could;

const node = doc.descendants((node) => node.isText && node.text === 'foobar' ? node : true);

Or you want to get the type of the first leaf node;

const type = doc.descendants((node) => node.isLeaf ? node.type : true);

…canning the graph if the handler returns something other then void | boolean
@marijnh
Copy link
Member

marijnh commented Oct 25, 2022

What I've been doing is just setting a flag (or storing a non-null result) when the search has finished, and putting a check for that at the top of the callback, making it return false right away. That seems to cover the cases where this is necessary with less complication.

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

Successfully merging this pull request may close these issues.

2 participants