1
0
mirror of https://github.com/bitwarden/browser.git synced 2024-12-01 13:13:36 +01:00

add daysRemaining util function and unit tests

This commit is contained in:
William Martin 2023-06-30 10:25:54 -04:00
parent 1c39938cda
commit 93691e725f
No known key found for this signature in database
GPG Key ID: A65ACD91BADF316B
2 changed files with 30 additions and 0 deletions

View File

@ -358,4 +358,25 @@ describe("Utils Service", () => {
expect(actual.protocol).toBe("http:");
});
});
describe("daysRemaining", () => {
const now = new Date(2023, 9, 2);
jest.spyOn(Date, "now").mockReturnValue(now.getTime());
it("should return 0 for equal dates", () => {
expect(Utils.daysRemaining(new Date(2023, 9, 2))).toBe(0);
});
it("should return 0 for dates in the past", () => {
expect(Utils.daysRemaining(new Date(2020, 5, 11))).toBe(0);
expect(Utils.daysRemaining(new Date(2023, 9, 1))).toBe(0);
});
it("should handle future dates", () => {
expect(Utils.daysRemaining(new Date(2023, 9, 3))).toBe(1);
expect(Utils.daysRemaining(new Date(2023, 10, 12))).toBe(41);
// leap year
expect(Utils.daysRemaining(new Date(2024, 9, 2))).toBe(366);
});
});
});

View File

@ -538,6 +538,15 @@ export class Utils {
return of(undefined).pipe(switchMap(() => generator()));
}
/**
* Return the number of days remaining before a target date arrives.
* Returns 0 if the day has already passed.
*/
static daysRemaining(targetDate: Date): number {
const diffTime = targetDate.getTime() - Date.now();
return Math.max(0, Math.round(diffTime / (1000 * 60 * 60 * 24)));
}
private static isAppleMobile(win: Window) {
return (
win.navigator.userAgent.match(/iPhone/i) != null ||