Home > Software engineering >  How to get out of function inside traverseInOrder method of bts in js?
How to get out of function inside traverseInOrder method of bts in js?

Time:11-22

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
    })

CodePudding user response:

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;
}
  • Related