Created
December 5, 2017 07:47
-
-
Save macabreb0b/9ad2cb3774b3310eb00301c9bbd1a24d to your computer and use it in GitHub Desktop.
Movie Title Typeahead in JS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MovieTypeaheadNode { | |
constructor(parent, value) { | |
this.value = value; | |
this.parent = parent; | |
this.children = []; | |
this.matchingMovies = []; | |
} | |
addChild(letter) { | |
let child = this.childWithValue(letter); | |
if (!child) { | |
child = new MovieTypeaheadNode(this, letter); | |
this.children.push(child); | |
} | |
return child; | |
} | |
childWithValue(letter) { | |
for (var idx in this.children) { | |
let child = this.children[idx]; | |
if (child.value == letter) { | |
return child; | |
} | |
} | |
return null; | |
} | |
addMatchingMovie(movie) { | |
this.matchingMovies.push(movie) | |
if (this.parent) { | |
this.parent.addMatchingMovie(movie); | |
} | |
} | |
} | |
export class MovieTypeahead { | |
constructor(movieList) { | |
this.movieList = movieList; | |
this.rootNode = new MovieTypeaheadNode(null, ''); | |
// fill words | |
movieList.forEach(movie => { | |
var currentNode = this.rootNode; | |
movie.title.toLowerCase().split('').forEach((letter, index) => { | |
currentNode = currentNode.addChild(letter) | |
if (index == movie.title.length - 1) { | |
// add '' node to indicate end of word | |
currentNode.addChild('') | |
// add word to this and all others in backwards path | |
currentNode.addMatchingMovie(movie) | |
} | |
}) | |
}) | |
} | |
findMatchingMovies(query) { | |
var matches = []; | |
var currentNode = this.rootNode; | |
for (var idx = 0; idx < query.length; idx++) { | |
const letter = query[idx].toLowerCase(); | |
currentNode = currentNode.childWithValue(letter) | |
if (currentNode == null) return []; | |
} | |
return currentNode.matchingMovies | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment