Skip to content

Commit

Permalink
Merge pull request #1 from EvanPerreau/dev
Browse files Browse the repository at this point in the history
Adding string support for durations on start method of Delay class
  • Loading branch information
EvanPerreau authored Jun 3, 2024
2 parents 41dc074 + 91bafc5 commit 1e996b8
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 3 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "delay-actions",
"version": "1.0.5",
"version": "1.0.6",
"main": "dist/delay.js",
"types": "dist/delay.d.ts",
"author": "Evan Perreau",
Expand Down
33 changes: 31 additions & 2 deletions src/delay.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,11 +30,13 @@ export class Delay {

/**
* Starts a delay for the specified duration.
* @param ms The duration of the delay in milliseconds.
* @param duration The duration of the delay in milliseconds or a string (e.g., "1m", "2s", "1h").
* @param action The action to execute when the delay is complete.
* @returns A promise that resolves when the delay is complete.
*/
async start(ms: number, action: () => void): Promise<void> {
async start(duration: number | string, action: () => void): Promise<void> {
const ms = typeof duration === 'string' ? this.durationToMilliseconds(duration) : duration;

return new Promise((resolve) => {
this._remainingSinceLastStart = ms;
this._startTime = Date.now();
Expand Down Expand Up @@ -85,4 +87,31 @@ export class Delay {
this._isPaused = false;
}
}

// --------------------
// Private methods
// --------------------

/**
* Converts a duration string to milliseconds.
* @param duration The duration string (e.g., "1m", "2s", "1h").
* @returns The duration in milliseconds.
*/
private durationToMilliseconds(duration: string): number {
const units = duration.slice(-1);
const value = Number(duration.slice(0, -1));

switch (units) {
case 's':
return value * 1000;
case 'm':
return value * 1000 * 60;
case 'h':
return value * 1000 * 60 * 60;
case 'd':
return value * 1000 * 60 * 60 * 24;
default:
throw new Error(`Unknown time unit: ${units}`);
}
}
}
8 changes: 8 additions & 0 deletions tests/delay.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,14 @@ describe('Delay', () => {
expect(elapsedTime).toBeGreaterThanOrEqual(ms);
});

it('should start and resolve after specified time (with time in string)', async () => {
const startTime = Date.now();
await delay.start('3s', () => {});
const endTime = Date.now();
const elapsedTime = endTime - startTime;
expect(elapsedTime).toBeGreaterThanOrEqual(3000);
});

it('should pause and resume correctly', async () => {
const ms = 2000; // 2 secondes
await delay.start(ms, () => {});
Expand Down

0 comments on commit 1e996b8

Please sign in to comment.