diff --git a/packages/easy/src/index.ts b/packages/easy/src/index.ts index bd8781adf..335773764 100644 --- a/packages/easy/src/index.ts +++ b/packages/easy/src/index.ts @@ -110,6 +110,7 @@ export * from './utils/Log'; export * from './utils/Mapper'; export * from './utils/Promise'; export * from './utils/Property'; +export * from './utils/Seconds'; export * from './utils/State'; export * from './utils/Sentence'; export * from './utils/Traverse'; diff --git a/packages/easy/src/utils/Seconds.ts b/packages/easy/src/utils/Seconds.ts new file mode 100644 index 000000000..4b0482e1c --- /dev/null +++ b/packages/easy/src/utils/Seconds.ts @@ -0,0 +1,24 @@ +import { ifTrue } from './If'; +import { toList } from '../types/List'; + +export const second = { + toDuration: (s: number) => { + const seconds = s % 60; + const minutes = Math.floor(s / 60) % 60; + const hours = Math.floor(s / 3600) % 24; + const days = Math.floor(s / 86400); + return { days, hours, minutes, seconds }; + }, + + toText: (s: number) => { + const { days, hours, minutes, seconds } = second.toDuration(s); + return toList( + ifTrue(days, d => `${d}d`), + ifTrue(hours, h => `${h}h`), + ifTrue(minutes, m => `${m}m`), + ifTrue(days + hours + minutes === 0, `${seconds}s`) + ) + .mapDefined(s => s) + .join(' '); + }, +}; diff --git a/packages/easy/test/utils/Seconds.test.ts b/packages/easy/test/utils/Seconds.test.ts new file mode 100644 index 000000000..234f7e9ae --- /dev/null +++ b/packages/easy/test/utils/Seconds.test.ts @@ -0,0 +1,27 @@ +import { second } from '../../src'; + +describe('Seconds', () => { + const { toDuration } = second; + + test('split', () => { + expect(toDuration(0)).toEqual({ days: 0, hours: 0, minutes: 0, seconds: 0 }); + expect(toDuration(1)).toEqual({ days: 0, hours: 0, minutes: 0, seconds: 1 }); + expect(toDuration(60)).toEqual({ days: 0, hours: 0, minutes: 1, seconds: 0 }); + expect(toDuration(3600)).toEqual({ days: 0, hours: 1, minutes: 0, seconds: 0 }); + expect(toDuration(86400)).toEqual({ days: 1, hours: 0, minutes: 0, seconds: 0 }); + expect(toDuration(86401)).toEqual({ days: 1, hours: 0, minutes: 0, seconds: 1 }); + expect(toDuration(86461)).toEqual({ days: 1, hours: 0, minutes: 1, seconds: 1 }); + expect(toDuration(90061)).toEqual({ days: 1, hours: 1, minutes: 1, seconds: 1 }); + }); + + test('toText', () => { + expect(second.toText(0)).toBe('0s'); + expect(second.toText(1)).toBe('1s'); + expect(second.toText(60)).toBe('1m'); + expect(second.toText(3600)).toBe('1h'); + expect(second.toText(86400)).toBe('1d'); + expect(second.toText(86401)).toBe('1d'); + expect(second.toText(86461)).toBe('1d 1m'); + expect(second.toText(90061)).toBe('1d 1h 1m'); + }); +});