Skip to content

Instantly share code, notes, and snippets.

@gwillz
Last active September 27, 2018 02:06
Show Gist options
  • Save gwillz/f0cfe2a203c5d4e61443d006cf595092 to your computer and use it in GitHub Desktop.
Save gwillz/f0cfe2a203c5d4e61443d006cf595092 to your computer and use it in GitHub Desktop.
ES6 tagged template string for inline date fomatting
/**
* This doesn't _need_ to use moment.
* It's just the library that this project is using.
* Luxon or date-fns could also drop in neatly.
*/
const moment = require('moment')
// This a bad name, as is 'format', so idk.
function inline(literals, ...parts) {
let join = '';
let locations = {};
// collecting part locations
// 'abc ${a}|fmt| abc ${b} abc'
// becomes:
// 'abc |||fmt| abc || abc||'
for (let i in literals) {
join += literals[i] + '||'; // this marks non-formatted values
locations[join.length - 2] = parts[i];
}
console.log(join)
// regex offsets will match locations, format appropriately
// matching '||' or '|||fmt|'
return join.replace(/\|\|(?:\|([^|]*)\|)?/g, (m, fmt, i) => (
moment.isMoment(locations[i])
? locations[i].format(fmt)
: (locations[i] || '')
));
}
// test
if (require.main === module) {
let m = moment(new Date());
let mm = moment(new Date(1111234567890));
let mmm = 'I am not a moment';
console.log(inline`
the date is ${m}|DD MMM YYYY|
another ${mm}|ddd|
<p>lastly ${mmm}</p>
`)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment