Add "Random Ron - No Dup" project

This commit is contained in:
Andrea Fazzi 2024-08-07 17:49:49 +02:00
parent 227287c624
commit b0956c7ece
4 changed files with 80 additions and 0 deletions

View file

@ -15,6 +15,7 @@ func main() {
mux.Handle("GET /character-count/", http.StripPrefix("/character-count", http.FileServer(http.Dir("character-count"))))
mux.Handle("GET /character-word-count/", http.StripPrefix("/character-word-count", http.FileServer(http.Dir("character-word-count"))))
mux.Handle("GET /random-ron/", http.StripPrefix("/random-ron", http.FileServer(http.Dir("random-ron"))))
mux.Handle("GET /random-ron-no-dup/", http.StripPrefix("/random-ron-no-dup", http.FileServer(http.Dir("random-ron-no-dup"))))
log.Println("Start the web server...")
err := http.ListenAndServe(":8080", mux)

View file

@ -0,0 +1,12 @@
# Random Ron
A site that displays a random Ron Swanson quote (from the show Parks
and Recreation) using the [Ron Swanson Quotes
API](https://github.com/jamesseanwright/ron-swanson-quotes). Note that
if the same quote gets returned from the API in the last 50 quotes,
the app skip it and fetch another one instead.
# Reference
* https://leanwebclub.com/learn/js-essentials/project-random-ron-no-duplicates

View file

@ -0,0 +1,19 @@
<!DOCTYPE html>
<html lang="en" data-bs-theme="dark">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/water.css@2/out/water.css">
<title>Random Ron No Duplicates</title>
</head>
<body>
<h1>Random Ron No Duplicates</h1>
<blockquote aria-live="polite"></blockquote>
<p>
<button id="get-quote">More Ron</button>
</p>
<script src="script.js"></script>
</body>
</html>

View file

@ -0,0 +1,48 @@
const MAX_QUOTES = 50;
let blockquote = document.querySelector('blockquote');
let button = document.querySelector('button#get-quote');
let lastQuotes = [];
function getQuote () {
blockquote.textContent = `Getting a fresh quote avoiding duplicates...`;
fetch('https://ron-swanson-quotes.herokuapp.com/v2/quotes').then(function (response) {
if (response.ok) {
return response.json();
}
throw response.status;
}).then(function (data) {
console.log(`Last quotes in array: ${lastQuotes.length}`);
if ( lastQuotes.length > MAX_QUOTES - 1 ) {
lastQuotes.shift();
}
let quote = data[0];
if ( !lastQuotes.includes(quote) ) {
blockquote.innerText = quote;
lastQuotes.push(quote);
} else {
console.log('Hit a dup! Re-fetching...', quote);
getQuote();
return;
}
}).catch(function (error) {
console.warn(error);
});
}
button.addEventListener('click', function (event) {
getQuote();
});
getQuote();