diff --git a/js-essentials/main.go b/js-essentials/main.go index f3ec7f0..d570d43 100644 --- a/js-essentials/main.go +++ b/js-essentials/main.go @@ -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) diff --git a/js-essentials/random-ron-no-dup/README.md b/js-essentials/random-ron-no-dup/README.md new file mode 100644 index 0000000..b4a91ef --- /dev/null +++ b/js-essentials/random-ron-no-dup/README.md @@ -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 + diff --git a/js-essentials/random-ron-no-dup/index.html b/js-essentials/random-ron-no-dup/index.html new file mode 100644 index 0000000..af478e7 --- /dev/null +++ b/js-essentials/random-ron-no-dup/index.html @@ -0,0 +1,19 @@ + + +
+ + + ++ +
+ + + + + diff --git a/js-essentials/random-ron-no-dup/script.js b/js-essentials/random-ron-no-dup/script.js new file mode 100644 index 0000000..0a726cc --- /dev/null +++ b/js-essentials/random-ron-no-dup/script.js @@ -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(); + + + + +