“Good Morning, Dave” — Creating a simple time-based greeting for your users using Node
The longer I’ve been writing code, the more appreciation I have when developers go a little bit further to make your experience enjoyable. Surprisingly, having a friendly greeting for your users upon login is a simple way to add a personalized touch to your application. Here’s my approach using Node.
We’re going to store this in a function called timedGreeting that we can pass in a name and optional Date object.
We’re also going to assume the following hour ranges:
Morning — 4 AM to Noon (04:00–12:00)
Afternoon — Noon to 5 PM (12:00–17:00)
Evening — 5 PM to 4 AM (17:00–04:00)
You can adjust your time ranges to reflect what makes more sense to you.
Grab this code and throw it in your projects:
/**
* Generates a greeting based on the time of day.
* @param {string} name - a name (optional).
* @param {Date} date - a date (optional).
* @returns {string} A friendly timed greeting.
*/
export const timedGreeting = (name?: string, date?: Date): string => {
if (!date) { date = new Date(); }
const time: number = date.getHours();
const suffix: string = name ? `, ${ name }` : '';
const timeOfDay: string = ( time < 12 &&…