Created
October 23, 2017 13:28
-
-
Save epzee/e6056809c4146b7f2a61f91167ba4139 to your computer and use it in GitHub Desktop.
This file contains 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
// Add your javascript here | |
const endpoint = 'https://jsonmock.hackerrank.com/api/movies/search/'; | |
const input = document.getElementById('q'); | |
const form = document.getElementById('search_form'); | |
const list = document.getElementById('results'); | |
form.addEventListener('submit', async (e) => { | |
e.preventDefault(); | |
const title = input.value; | |
const data = await getData(title); | |
updateResults(data); | |
}) | |
const fetchPage = async (title, pageNumber) => { | |
const req = await fetch(`${endpoint}?Title=${title}&page=${pageNumber}`); | |
const res = await req.json(); | |
return res; | |
} | |
const sortByTitle = (arr) => { | |
return arr.sort((a, b) => { | |
if (a.Title < b.Title) { | |
return -1; | |
} | |
if (a.Title > b.Title) { | |
return 1; | |
} | |
return 0; | |
}); | |
} | |
const getAllResults = async (query, initialReq) => { | |
const remainingPages = []; | |
for (let i = 2; i <= initialReq.total_pages; i++) { | |
remainingPages.push(fetchPage(query, i)); | |
} | |
const remaining = await Promise.all(remainingPages); | |
let results = initialReq.data; | |
remaining.forEach((page) => { | |
results = results.concat(...page.data); | |
}); | |
return sortByTitle(results); | |
} | |
const getData = async (query) => { | |
const initialReq = await fetchPage(query, 1); | |
if (initialReq.total_pages === 1) { | |
return sortByTitle(initialReq.data); | |
} | |
return await getAllResults(query, initialReq); | |
} | |
const updateResults = (results) => { | |
const documentFragment = document.createDocumentFragment(); | |
list.innerHTML = ''; | |
results.forEach((movie) => { | |
const item = document.createElement('li'); | |
item.classList.add('list-group-item'); | |
item.innerHTML = movie.Title; | |
documentFragment.appendChild(item); | |
}); | |
list.appendChild(documentFragment); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment