jsmreese / moment-duration-format

Format function plugin for the Moment Duration object.
MIT License
968 stars 120 forks source link

"largest" option to only display largest n units #75

Closed gabrielgrant closed 6 years ago

gabrielgrant commented 7 years ago

Something equivalent to the largest option on HumanizeDuration.js would be useful -- this is somewhat similar to trim, except it removes the least significant units until there are at most largest elements present

weeco commented 6 years ago

Actually I am looking for exactly the same

jsmreese commented 6 years ago

Trying to pick up this project and give it some love, was just looking at this issue...

humanizeDuration(1000000000000)                  // '31 years, 8 months, 1 week, 19 hours, 46 minutes, 40 seconds'
humanizeDuration(1000000000000, { largest: 2 })  // '31 years, 8 month'

works because humanizeDuration controls the output template, adding commas as needed.

My plugin doesn't control the output template, so I'm left with a hanging comma here:

moment.duration(1.55, "days").format("d [days], h [hours], m [minutes], s [seconds]", { largest: 2 });
//"1 days, 13 hours, "

Any thoughts on how to handle that? Are you looking for the auto-comma-separated output of humanizeDuration?

jsmreese commented 6 years ago

On second thought, it seems like the cleanest thing to do if the largest option is turned on would be to not begin or end the formatted output with a comma or a space or a colon. That would take care of these issues.

gabrielgrant commented 6 years ago

@jsmreese thanks for taking a look at this! That sounds like it should work. To be clear, you're just talking about generating the string as you do today, then trimming before returning it, right?

jsmreese commented 6 years ago

I've pushed a new version of the plugin to the master branch. It's labeled as version 2.0.0b1 in the js file. This version implements largest as well as trim: "both" (which can be used in conjunction with largest). This version also extends the moment en locale so that duration unit strings will be auto-singularized. e.g. instead of outputting 1 minutes or 1 mins, the plugin will now automatically output 1 minute or 1 min. Basic documentation for the new options can be found in the js file in the default options section. I'll add documentation to the readme in the next few days. Once I've done that, added a few more tests, and reviewed the other open issues, I'll publish version 2.0.0.

gabrielgrant commented 6 years ago

Sounds great, thanks a lot! I'll try to integrate it this week to remove the hacky workaround I'm currently using

jsmreese commented 6 years ago

Closing this. Fixed in 6d2ff9e7779a62da620649810a24f11770fd07ff.