From 8d4a1d64268e48c80e92783707d4b21c9a5d5850 Mon Sep 17 00:00:00 2001 From: Sander Hoogendoorn Date: Sun, 15 Sep 2024 15:14:47 +0200 Subject: [PATCH] fix: addings seconds ago() utility method --- packages/easy/src/utils/Seconds.ts | 5 ++++- packages/easy/test/utils/Seconds.test.ts | 16 +++++++++++++++- 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/packages/easy/src/utils/Seconds.ts b/packages/easy/src/utils/Seconds.ts index 014cd50b..5e685a29 100644 --- a/packages/easy/src/utils/Seconds.ts +++ b/packages/easy/src/utils/Seconds.ts @@ -1,5 +1,6 @@ import { ifTrue } from './If'; import { toList } from '../types/List'; +import { DateTime } from '../domain/DateTime'; export const seconds = { toDuration: (s: number) => { @@ -10,10 +11,12 @@ export const seconds = { return { days, hours, minutes, seconds }; }, - toText: (s: number) => { + toText: (s: number): string => { const { days, hours, minutes, seconds: secs } = seconds.toDuration(s); return toList(ifTrue(days, `${days}d`), ifTrue(hours, `${hours}h`), ifTrue(minutes, `${minutes}m`), ifTrue(days + hours + minutes === 0, `${secs}s`)) .mapDefined(s => s) .join(' '); }, + + ago: (start: DateTime, end: DateTime = DateTime.now) => seconds.toText(end.diff(start, 'second')), }; diff --git a/packages/easy/test/utils/Seconds.test.ts b/packages/easy/test/utils/Seconds.test.ts index 9de8612b..d84f7611 100644 --- a/packages/easy/test/utils/Seconds.test.ts +++ b/packages/easy/test/utils/Seconds.test.ts @@ -1,4 +1,6 @@ -import { seconds } from '../../src'; +import { dt, seconds } from '../../src'; +import { DateTime } from 'luxon'; +import { mock } from '@thisisagile/easy-test'; describe('Seconds', () => { test('split', () => { @@ -22,4 +24,16 @@ describe('Seconds', () => { expect(seconds.toText(86461)).toBe('1d 1m'); expect(seconds.toText(90061)).toBe('1d 1h 1m'); }); + + test('ago', () => { + const start = dt('2021-01-01T00:00:00Z'); + const end = dt('2021-01-01T00:00:01Z'); + expect(seconds.ago(start, end)).toBe('1s'); + }); + + test('ago with default end', () => { + DateTime.now = mock.return(dt('2021-01-03T03:03:01Z')); + const start = dt('2021-01-06T00:00:00Z'); + expect(seconds.ago(start)).toBe('1348d 13h 13m'); + }); });