O'Reilly logo

Hands-On Data Structures and Algorithms with JavaScript by Kashyap Mukkamala

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Implementing the search() method

The search() method is even simpler and highly efficient with a complexity of O(n), where n is the length of the search input. The big O notation is something that will be covered in detail in a later chapter:

search(input) {    // get the whole tree    var currentNode = this.tree;    var curChar = input.slice(0,1);        // take first character    input = input.slice(1);   // keep extracting the sub-tree based on the current character    while(currentNode[curChar] && curChar){        currentNode = currentNode[curChar];        curChar = input.slice(0,1);        input = input.slice(1);    }    // reached the end and no sub-tree found    // e.g. no data found    if (curChar && !currentNode[curChar]) {        return {};    }    // return the node found    return currentNode;}

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required