Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get out of function inside traverseInOrder method of bts in js?

I am using bts from https://www.npmjs.com/package/@datastructures-js/binary-search-tree.
I don’t want to go through the whole tree using traverseInOrder method , how can I stop and go out of function after the condtition is true?

   bts.traverseInOrder(node =>{
         if(condition) return
    })

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

No, there is no early exit feature foreseen in that method.

You can still raise an error and capture it:

try {
    bts.traverseInOrder(node => {
        if (condition) throw new Error("exit");
    });
} catch(e) {
    if (e?.message != "exit") throw e; // It was a different error
}

Or else, define your own method. And in that case I would suggest the more modern generator-pattern instead of the callback pattern:

// Extend the API with this generator
Object.assign(BinarySearchTree.prototype, {
    *iterateInOrder() {
        function* iterateRecursive(current) {
            if (current === null) return;
            yield* iterateRecursive(current.getLeft());
            yield current;
            yield* iterateRecursive(current.getRight());
        }
        yield* iterateRecursive(this._root);
    }
});

And now you can use a for .. of loop:

for (let node of bst.iterateInOrder()) {
    if (condition) break;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading