Commit 6c989a43 authored by Sean Hammond's avatar Sean Hammond

Remove some code duplication

parent a57bc066
...@@ -42,31 +42,43 @@ function nHr(date, now) { ...@@ -42,31 +42,43 @@ function nHr(date, now) {
return '{} hr'.replace('{}', Math.floor(delta(date, now) / hour)); return '{} hr'.replace('{}', Math.floor(delta(date, now) / hour));
} }
// Cached DateTimeFormat instance, instantiating a DateTimeFormat is expensive. // Cached DateTimeFormat instances,
var dayAndMonthFormatter; // because instantiating a DateTimeFormat is expensive.
var formatters = {};
/**
* Efficiently return `date` formatted with `options`.
*
* This is a wrapper for Intl.DateTimeFormat.format() that caches
* DateTimeFormat instances because they're expensive to create.
*
* @returns {string}
*
*/
function format(date, options) {
var key = JSON.stringify(options);
var formatter = formatters[key];
if (!formatter) {
formatter = formatters[key] = new Intl.DateTimeFormat(undefined, options);
}
return formatter.format(date);
}
function dayAndMonth(date) { function dayAndMonth(date) {
if (!dayAndMonthFormatter) { return format(date, {
dayAndMonthFormatter = new Intl.DateTimeFormat(undefined, {
month: 'short', month: 'short',
day: '2-digit', day: '2-digit',
}); });
}
return dayAndMonthFormatter.format(date);
} }
// Cached DateTimeFormat instance, instantiating a DateTimeFormat is expensive.
var dayMonthAndYearFormatter;
function dayAndMonthAndYear(date) { function dayAndMonthAndYear(date) {
if (!dayMonthAndYearFormatter) { return format(date, {
dayMonthAndYearFormatter = new Intl.DateTimeFormat(undefined, {
day: '2-digit', day: '2-digit',
month: 'short', month: 'short',
year: 'numeric' year: 'numeric'
}); });
}
return dayMonthAndYearFormatter.format(date);
} }
var BREAKPOINTS = [ var BREAKPOINTS = [
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment