Ajax interview question for Ecocion
Forked from Tomas Morris's Pen Ajax Interview Question.
Forked from Tomas Morris's Pen Ajax Interview Question.
Forked from Tomas Morris's Pen Ajax Interview Question.
A Pen by Benjamin Flowers on CodePen.
Ajax interview question for Ecocion
Forked from Tomas Morris's Pen Ajax Interview Question.
Forked from Tomas Morris's Pen Ajax Interview Question.
Forked from Tomas Morris's Pen Ajax Interview Question.
A Pen by Benjamin Flowers on CodePen.
<h1>Most Popular Repo</h1> | |
<ul id="success"></ul> | |
<ul id="fail"></ul> |
/* USER | |
{ | |
... | |
"repos_url": <absolute url> | |
} | |
/* REPO | |
[{ | |
... | |
full_name: <string>, | |
stargazers_count: <number> | |
}] | |
*/ | |
/* | |
Given | |
*/ | |
var URL = "https://api.github.com/users/"; // Github API endpoint | |
var USERS = ["reecer", "Microsoft", "ecocion"]; // Github users. Are they all real? | |
USERS.forEach(getUser); | |
function getUser(user) { | |
// IF user exists, | |
// getRepos(data.repos_url); | |
// ELSE, | |
// call addFail(user) | |
fetch(URL + user) | |
.then(response => { | |
if (!response.ok) { | |
throw new Error(); | |
} | |
return response.json(); | |
}) | |
.then( data => { | |
getRepos(data.repos_url); | |
}) | |
.catch(error => { | |
addFail(user); | |
}); | |
} | |
function getRepos(repoUrl) { | |
// 1. Get all repos | |
// 2. Determine which repo is most popular (stargazers_count) | |
// 3. Call addSuccess with the most popular repo's name and stargazers_count | |
fetch(repoUrl) | |
.then(response => { | |
if (!response.ok) { | |
throw new Error(); | |
} | |
return response.json(); | |
}) | |
.then(data => { | |
var mostStars = -1; | |
var mostPopular; | |
data.forEach(repo => { | |
if (repo.stargazers_count > mostStars) { | |
mostStars = repo.stargazers_count; | |
mostPopular = repo.full_name; | |
} | |
}); | |
addSuccess(mostPopular, mostStars); | |
}); | |
/*$.getJSON(repoUrl, function(repoData) { | |
var mostStars = -1; | |
var mostPopular; | |
repoData.forEach(function(repo) { | |
if (repo.stargazers_count > mostStars) { | |
mostStars = repo.stargazers_count; | |
mostPopular = repo.full_name; | |
} | |
}); | |
addSuccess(mostPopular, mostStars); | |
});*/ | |
} | |
/* | |
Given | |
*/ | |
let $success = document.getElementById('success'); | |
let $fail = document.getElementById('fail'); | |
function addSuccess(repoName, starCount) { | |
let $listItem = document.createElement("li"); | |
$listItem.textContent = repoName + " - " + starCount; | |
$success.appendChild($listItem); | |
} | |
function addFail(user) { | |
let $listItem = document.createElement("li"); | |
$listItem.textContent = user; | |
$fail.appendChild($listItem); | |
} |
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> |
body { | |
font-family: "Segoe UI Semilight"; | |
} | |
h1 { | |
color: #2E6E9E; | |
font-size: 3em; | |
padding: 1em; | |
} | |
#fail { | |
color: red; | |
} | |
#success { | |
color: green; | |
} |