Skip to content

Instantly share code, notes, and snippets.

@Nijhazer
Created August 5, 2016 01:57
Show Gist options
  • Save Nijhazer/9aa9c7c74f9255618c5018fbd965f03d to your computer and use it in GitHub Desktop.
Save Nijhazer/9aa9c7c74f9255618c5018fbd965f03d to your computer and use it in GitHub Desktop.
/*
* Time for a little data structure and algorithm exercise.
*
* Websites commonly make use of a "search suggestion" feature.
* As you type, options are suggested to you based on what others
* have searched for in the past. For example, if I type 'Le',
* I will be presented with other things for which people have searched--
* other terms that begin with 'Le', such as "Levi", "Lego", and "Level".
* One way to accomplish this is by using a tree structure, breaking each previous
* search term into characters and then storing them in a tree, like so:
*
* *
* |
* -- L
* |
* -- e
* |
* -- v
* | |
* | -- e
* | | |
* | | -- l
* | |
* | -- i
* |
* -- g
* |
* -- o
*
* In this exercise, we want you to build such a tree structure.
* It will have a method called 'search', which will always return an array
* of any letters that could follow the provided search term, based on what's been
* searched in the past.
*
* tree.search('Levi'); // []
* tree.search('Lego'); // []
* tree.search('Le'); // ['g', 'v']
* tree.search('Leg'); // ['o']
*
* Use the provided Node and WordTree objects, then build the
* search method so that it passes the provided tests.
*/
const expect = require('chai').expect
class Node {
constructor(data) {
this.data = data
this.parent = null
this.children = []
}
}
class WordTree {
constructor() {
this.root = new Node({})
}
search(word, nodes) {
// your code goes here-- good luck!
}
}
let tree = new WordTree()
expect(tree.search('Levi')).to.deep.equal([])
expect(tree.search('Level')).to.deep.equal([])
expect(tree.search('Lego')).to.deep.equal([])
expect(tree.search('Le')).to.deep.equal(['v', 'g'])
expect(tree.search('Leg')).to.deep.equal(['o'])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment