From 6e7e77aba451a9c593734edff33b47f8b9d0580a Mon Sep 17 00:00:00 2001 From: uri Date: Fri, 15 Dec 2023 18:09:35 +0200 Subject: [PATCH] assert-async --- src/debug.test.ts | 19 +++++++++++++++++-- src/debug.ts | 18 +++++++++++++----- 2 files changed, 30 insertions(+), 7 deletions(-) diff --git a/src/debug.test.ts b/src/debug.test.ts index 187b6b8..a96d2df 100644 --- a/src/debug.test.ts +++ b/src/debug.test.ts @@ -5,6 +5,7 @@ import { spy, } from "https://deno.land/std@0.195.0/testing/mock.ts"; +import { assertEquals } from "https://deno.land/std@0.195.0/assert/assert_equals.ts"; import { assertThrows } from "https://deno.land/std@0.174.0/testing/asserts.ts"; import { sleep } from "./time.ts"; @@ -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); }); diff --git a/src/debug.ts b/src/debug.ts index 7ef0674..94035a5 100644 --- a/src/debug.ts +++ b/src/debug.ts @@ -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 = (x: T) => { console.log(currentLocation(3), x); @@ -62,7 +63,14 @@ export const timeit = ( return result; }) as F; -export const assert = (condition: (_: T) => boolean, errorMessage: string) => - sideEffect((x: T) => { - if (!condition(x)) throw new Error(errorMessage); - }); +export const assert = ( + condition: (_: T) => boolean | Promise, + errorMessage: string, +) => + pipe( + pairRight(condition), + ([value, passed]) => { + if (!passed) throw new Error(errorMessage); + return value; + }, + );