Skip to content

Commit

Permalink
assert-async
Browse files Browse the repository at this point in the history
  • Loading branch information
uriva committed Dec 15, 2023
1 parent 60cfff8 commit 6e7e77a
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 7 deletions.
19 changes: 17 additions & 2 deletions src/debug.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
spy,
} from "https://deno.land/[email protected]/testing/mock.ts";

import { assertEquals } from "https://deno.land/[email protected]/assert/assert_equals.ts";
import { assertThrows } from "https://deno.land/[email protected]/testing/asserts.ts";
import { sleep } from "./time.ts";

Expand Down Expand Up @@ -45,8 +46,22 @@ Deno.test("asyncTimeit with args", async () => {

Deno.test("assert", () => {
const err = "not greater than 7";
const condition = (x: number) => x > 7;
assertThrows(() => {
assert((x: number) => x > 7, err)(3);
assert(condition, err)(3);
});
assert((x: number) => x > 7, err)(10);
assert(condition, err)(10);
});

Deno.test("assert async", async () => {
const err = "not greater than 7";
const condition = (x: number) => Promise.resolve(x > 7);
let thrown = false;
try {
await assert(condition, err)(3);
} catch (_) {
thrown = true;
}
assertEquals(thrown, true);
await assert(condition, err)(10);
});
18 changes: 13 additions & 5 deletions src/debug.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { Func, ReturnTypeUnwrapped } from "./typing.ts";

import { currentLocation } from "./trace.ts";
import { sideEffect } from "./composition.ts";
import { pairRight } from "./juxt.ts";
import { pipe } from "./composition.ts";

export const sideLog = <T>(x: T) => {
console.log(currentLocation(3), x);
Expand Down Expand Up @@ -62,7 +63,14 @@ export const timeit = <F extends Func>(
return result;
}) as F;

export const assert = <T>(condition: (_: T) => boolean, errorMessage: string) =>
sideEffect((x: T) => {
if (!condition(x)) throw new Error(errorMessage);
});
export const assert = <T>(
condition: (_: T) => boolean | Promise<boolean>,
errorMessage: string,
) =>
pipe(
pairRight(condition),
([value, passed]) => {
if (!passed) throw new Error(errorMessage);
return value;
},
);

0 comments on commit 6e7e77a

Please sign in to comment.