Last active
November 29, 2017 11:49
-
-
Save vaidd4/022f86e1cfbf65b7ef7ecae1d3ee980c to your computer and use it in GitHub Desktop.
Simple durations stringifier for Moment.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Simple durations stringifier for Moment.js | |
* Return a human readable string representing the given moment duration | |
* Based on @cogwirrel comment (https://github.com/moment/moment/issues/348#issuecomment-346233713) | |
* | |
* TODO: | |
* - Add simple lang support (fr, en) | |
*/ | |
function stringifyDuration (duration) { | |
// Simple implementation of https://lodash.com/docs#dropWhile | |
const dropWhile = (arr, fn) => arr.slice(arr.findIndex(v => !fn(v))) | |
// Split the duration into parts, and drop the most significant parts with a value of 0 | |
const durationParts = dropWhile([ | |
{ value: duration.years(), unit: 'an' }, | |
{ value: duration.months(), unit: 'mois', iv: true }, // if the unit is invariable | |
{ value: duration.days(), unit: 'jour' }, | |
{ value: duration.hours(), unit: 'heure' }, | |
{ value: duration.minutes(), unit: 'minute' }, | |
{ value: duration.seconds(), unit: 'seconde' }, | |
{ value: duration.milliseconds(), unit: 'milliseconde' } | |
], (part) => part.value === 0) | |
// Display up to two of the most significant remaining parts | |
return durationParts.slice(0, 2).map((part) => ( | |
`${part.value} ${part.unit + (!part.iv && part.value > 1 ? 's' : '')}` | |
)).join(', ') | |
} | |
stringifyDuration(moment.duration(26, 'hours')) // => "1 day, 2 hours" | |
/** | |
* [JS Standard](https://standardjs.com/demo.html?gist=022f86e1cfbf65b7ef7ecae1d3ee980c) | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment