Skip to content

Commit

Permalink
feat: Sleep function
Browse files Browse the repository at this point in the history
  • Loading branch information
201flaviosilva committed May 7, 2024
1 parent 3e0720c commit 5793521
Show file tree
Hide file tree
Showing 3 changed files with 63 additions and 0 deletions.
2 changes: 2 additions & 0 deletions src/main.js
Expand Up @@ -22,6 +22,7 @@ import { randomFloat, randomInt, randomNumber } from "./randomNumber.js";
import { randomString } from "./randomString.js";
import { randomWalk } from "./randomWalk.js";
import { reverseString } from "./reverseString.js";
import { sleep } from "./sleep.js";

export {
Arrays,
Expand Down Expand Up @@ -53,5 +54,6 @@ export {
randomString,
randomWalk,
reverseString,
sleep,
};

24 changes: 24 additions & 0 deletions src/sleep.js
@@ -0,0 +1,24 @@
/**
* Pause the thread for the determined time
*
* @example
* sleep();
* sleep(2000);
*
* @example
* (async function () {
* console.log("Beep");
* await sleep(5000);
* console.log("Boop");
* })();
*
* @param {number} time - time in ms to pause the thread
* @returns {any}
*/
export async function sleep(time = 1000) {
if (typeof time !== "number" || time < 0 || isNaN(time)) {
throw new Error("Time must be a non-negative number");
}
return new Promise(resolve => setTimeout(resolve, time));
}

37 changes: 37 additions & 0 deletions tests/sleep.test.js
@@ -0,0 +1,37 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { sleep } from "./src/main";

describe("sleep.js", () => {
beforeEach(vi.useFakeTimers);
afterEach(vi.clearAllTimers);

it("should return a promise", () => {
expect(sleep()).toBeInstanceOf(Promise);
});

it("should pause the thread for the determined time", async () => {
const promise = sleep(10000);
expect(vi.getTimerCount()).toBe(1);
vi.advanceTimersByTime(10000);
expect(promise).resolves;
expect(vi.getTimerCount()).toBe(0);
});

it("throws an error for negative time", async () => {
try {
await sleep(-100);
throw new Error("Promise should not resolve");
} catch (error) {
expect(error.message).toBe("Time must be a non-negative number");
}
});

it("throws an error for non-numeric time", async () => {
try {
await sleep("abc");
throw new Error("Promise should not resolve");
} catch (error) {
expect(error.message).toBe("Time must be a non-negative number");
}
});
});

0 comments on commit 5793521

Please sign in to comment.