Skip to content

Commit

Permalink
feat: allow removing of zeroes for durations
Browse files Browse the repository at this point in the history
  • Loading branch information
JKamue committed Jan 22, 2025
1 parent 0d267fa commit 49d1853
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 0 deletions.
10 changes: 10 additions & 0 deletions src/duration.js
Original file line number Diff line number Diff line change
Expand Up @@ -862,6 +862,16 @@ export default class Duration {
return clone(this, { values: negated }, true);
}

/**
* Removes all units with values equal to 0 from this Duration.
* @example Duration.fromObject({ years: 2, days: 0, hours: 0, minutes: 0 }).removeZeroes().toObject() //=> { years: 2 }
* @return {Duration}
*/
removeZeroes() {
const vals = removeZeroes(this.toObject());
return clone(this, { values: vals }, true);
}

/**
* Get the years.
* @type {number}
Expand Down
20 changes: 20 additions & 0 deletions test/duration/units.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -359,3 +359,23 @@ test("Duration#valueOf value of the duration with lower and higher order units",
const dur = Duration.fromObject({ days: 2, seconds: 1 });
expect(dur.valueOf()).toBe(172801000);
});

//------
// #removeZeroes()
//-------

test("Duration#removeZeroes removes zero units", () => {
expect(Duration.fromObject({ years: 2, days: 12, hours: 0 }).removeZeroes().toObject()).toEqual({
years: 2,
days: 12,
});
expect(
Duration.fromObject({ years: 2, days: 12, weeks: 0, hours: 0, milliseconds: 1 })
.removeZeroes()
.toObject()
).toEqual({
years: 2,
days: 12,
milliseconds: 1,
});
});

0 comments on commit 49d1853

Please sign in to comment.