Skip to content

Instantly share code, notes, and snippets.

@blrobin2
Created May 30, 2020 13:15
Show Gist options
  • Save blrobin2/5a156e00c093b9d6be144fb4cb1c6d58 to your computer and use it in GitHub Desktop.
Save blrobin2/5a156e00c093b9d6be144fb4cb1c6d58 to your computer and use it in GitHub Desktop.
A way of representing the concept of a MAX_DATE or END_OF_TIME constant
const END_OF_TIME = new Date(parseInt('9'.repeat(15), 10))
// Thu Sep 26 33658 21:46:39 GMT-0400 (Eastern Daylight Time)
// Example usage: default for date comparisons where you want to ensure the default is greater than
// any of the provided dates
const dateFromMMDDYYYY = mmddyyyy => new Date(Date.parse(mmddyyyy))
const dates = ['02/29/1984', '03/01/2055', '02/29/2244']
const earliest_date = dates.map(dateFromMMDDYYYY)
.reduce(
(earliest, date) => date < earliest ? date : earliest,
END_OF_TIME
);
// Of course in JavaScript, you could just do this:
dates.reduce((earliest, date) => date < earliest ? date : earliest)
// But if dates is an empty array, you'll get:
// Uncaught TypeError: Reduce of empty array with no initial value at Array.reduce
// You can think of this as a variation of the Null Object Pattern: https://en.wikipedia.org/wiki/Null_object_pattern
// That is, no matter what data you'll be dealing with, you'll always end up with a Date, preventing scattering your
// code base with null checks:
if (earliest_date != null) {
earliest_date.getFullYear() // or some other date check
}
// or, more accurately in a Duck Typing world:
if (earliest_date != null && typeof earliest_date.getFullYear === 'function') {
earliest_date.getFullYear()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment