Skip to content

Instantly share code, notes, and snippets.

@smitp
Last active December 31, 2020 11:01
Show Gist options
  • Save smitp/fbef1ba0f656e1c337f90154eab1ff4e to your computer and use it in GitHub Desktop.
Save smitp/fbef1ba0f656e1c337f90154eab1ff4e to your computer and use it in GitHub Desktop.
[JS-Interview] Problem 1
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