I have created a random quote generator for my Angular app. The component code looks like this:
qotd = this.quotes[Math.floor(Math.random() * this.quotes.length)];
That's pulling from data that looks like this:
quotes = [
{
quote: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus euismod magna magna, euismod tincidunt libero dignis.",
author: 'Sorato Violasa'
},
{
quote: "Nullam dignissim accumsan magna vitae rhoncus. Phasellus euismod magna magna, euismod tincidunt libero dignis.",
author: 'Vito Dignaora'
},
{
quote: "In tincidunt imperdiet augue, quis sollicitudin mi tincidunt ut.",
author: 'Hivalo Amettioa'
},
{
quote: "hasellus accumsan erat vitae enim blandit, quis euismod ipsum sollicitudin.",
author: 'Grasha Plojiva'
},
];
And then in my view I do this:
<div class="quotes">
<p class="quote">
{{qotd.quote}} <br><br>
~ {{qotd.author}}
</p>
</div>
The thing is, right now this will generate a new quote every time the component re-loads, which can be multiple times within a single session. What I realize now would be better is to make this a daily quote generator. So it would only generate a new quote if the date changes. What's the simplest way to implement something like this? It's easy enough to generate the date and day of the week, like this:
date = new Date();
dayNumber = this.date.getDay();
But how would I compute when the day of the week changes in order to fire off a new instance?
Consider a scheme where the server prepares 3 quotes: one for yesterday, today and tomorrow. Each new day, yesterday is removed and a new tomorrow added. That way the quote on the client can be changed just after midnight client local time and everyone sees the same quote on their same local day.
Nowhere on Earth that is more than 14 hours different to UTC, so if server bases the keys on UTC every client will have a suitable number of quotes and the entire quote database isn't pushed to every client every time it changes.
var quotes = {
'20171012':{quote:'one',author:'fred'},
'20171013':{quote:'two',author:'mary'},
'20171014':{quote:'three',author:'sue'}
};
function showQuote(quotes) {
var d = new Date();
var key = '' + d.getFullYear() +
('0'+(d.getMonth()+1)).slice(-2) +
('0'+d.getDate()).slice(-2);
return quotes[key]
}
// On 2017-10-13 shows quote: two, author: mary
console.log(showQuote(quotes));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With