Created
December 1, 2022 17:09
-
-
Save AhmedHelalAhmed/76dece511e0aec72d111a10d307abbd7 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
const https = require('https'); | |
/* | |
* Complete the function below. | |
* Use console.log to print the result, you should not return from the function. | |
*/ | |
function getMovieTitles(substr) { | |
if (substr === '') | |
return '' | |
let titles = [] | |
const url = `https://jsonmock.hackerrank.com/api/movies/search/?Title=${substr}` | |
const makeRestTasks = (totalPage, url) => { | |
if (totalPage <= 1) | |
return [] | |
let tasks = [] | |
while (totalPage > 1) { | |
tasks.push( | |
q(`${url}&page=${totalPage}`) | |
) | |
totalPage -= 1 | |
} | |
return tasks | |
} | |
const q = url => { | |
return new Promise((resolve, reject) => { | |
https.get(url, res => { | |
res.on('data', str => { | |
let data = JSON.parse(str) | |
resolve(data) | |
}) | |
}).on('error', err => { | |
reject(err) | |
}) | |
}) | |
} | |
q(url) | |
.then(firstPageData => { | |
let restTasks = makeRestTasks(firstPageData.total_pages, url) | |
Promise.all(restTasks) | |
.then(result => { | |
let tmp = [] | |
result.map(item => { | |
tmp = [...tmp, ...item.data] | |
}) | |
titles = [...firstPageData.data, ...tmp] | |
.map(item => item.Title) | |
.sort((a, b) => a.localeCompare(b)) | |
console.log(titles) | |
}) | |
.catch(err => { | |
console.log(err) | |
}) | |
}) | |
.catch(err => { | |
console.log(err) | |
}) | |
} | |
getMovieTitles('spiderman') | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment