Skip to content

Commit

Permalink
fix: adding second utility.
Browse files Browse the repository at this point in the history
  • Loading branch information
Sander Hoogendoorn committed Sep 13, 2024
1 parent 1beaffb commit a6132ab
Show file tree
Hide file tree
Showing 3 changed files with 52 additions and 0 deletions.
1 change: 1 addition & 0 deletions packages/easy/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down
24 changes: 24 additions & 0 deletions packages/easy/src/utils/Seconds.ts
Original file line number Diff line number Diff line change
@@ -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(' ');
},
};
27 changes: 27 additions & 0 deletions packages/easy/test/utils/Seconds.test.ts
Original file line number Diff line number Diff line change
@@ -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');
});
});

0 comments on commit a6132ab

Please sign in to comment.