Last active
December 31, 2020 11:01
-
-
Save smitp/fbef1ba0f656e1c337f90154eab1ff4e to your computer and use it in GitHub Desktop.
[JS-Interview] Problem 1
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
function getRandomBool(n) { | |
var maxRandomCoeff = 1000; | |
if (n > maxRandomCoeff) n = maxRandomCoeff; | |
return Math.floor(Math.random() * maxRandomCoeff) % n === 0; | |
} | |
function renderArticle(article){ | |
console.log(`Rendered ${article}`); | |
} | |
//api to fetch a single article | |
function getArticle(articleId) { | |
return new Promise((resolve, reject) => { | |
setTimeout(() => { | |
if (getRandomBool(2)) { | |
reject(`Failed article ${articleId}`); | |
} else { | |
resolve(`Resolved article ${articleId}`); | |
// console.log(`resolving article ${articleId}`); | |
} | |
}, Math.random() * 1000); | |
}); | |
} | |
function getArticleIds(page) { | |
let ids = []; | |
const pageSize=10; | |
for (let i=0; i<pageSize; i++) { | |
ids.push(page*pageSize + i); | |
} | |
return new Promise((resolve, reject) => { | |
setTimeout(() => { | |
resolve(ids); | |
}, Math.random() * 1000); | |
}); | |
} | |
// An article should only be rendered only when all previous articles have been rendered. | |
// Fetch all articleIds and then render all articles as fast and efficiently as possible. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment