Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bflow/bc8c4189f1f5ecec5c03ea0055e857f8 to your computer and use it in GitHub Desktop.
Save bflow/bc8c4189f1f5ecec5c03ea0055e857f8 to your computer and use it in GitHub Desktop.
2-Ajax Interview Solution (JS Only)
<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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment