Skip to content

Commit

Permalink
fix-assert-typing
Browse files Browse the repository at this point in the history
  • Loading branch information
uriva committed Jan 10, 2025
1 parent 766c150 commit dea73c3
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 5 deletions.
6 changes: 6 additions & 0 deletions src/debug.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { assert, timeit, tryCatch } from "./debug.ts";
import { assertEquals, assertThrows } from "std-assert";
import { sleep } from "./time.ts";
import { throwerCatcherWithValue } from "./index.ts";
import { pipe } from "./composition.ts";

Deno.test("timeit", () => {
const logger = (x: string) => console.log(x);
Expand Down Expand Up @@ -53,6 +54,11 @@ Deno.test("assert", () => {
assert(condition, err)(10);
});

const _assertTyping: number = pipe(
(x: number) => x,
assert((x: number) => x > 3, "bla"),
)(7);

Deno.test("assert async", async () => {
const err = "not greater than 7";
const condition = (x: number) => Promise.resolve(x > 7);
Expand Down
15 changes: 10 additions & 5 deletions src/debug.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,14 @@ import type {
AsyncFunction,
Func,
IsAsync,
ParamOf,
ReturnTypeUnwrapped,
} from "./typing.ts";
import { pipe } from "./composition.ts";
import { pipe, sideEffect } from "./composition.ts";
import { pairRight } from "./juxt.ts";
import { isPromise } from "./promise.ts";
import { currentLocation } from "./trace.ts";
import { letIn } from "./operator.ts";

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

export const assert = <T>(
condition: (_: T) => boolean | Promise<boolean>,
export const assert = <F extends Func>(
condition: F,
errorMessage: string,
) =>
): true extends IsAsync<F> ? ((t: ParamOf<F>) => Promise<ParamOf<F>>)
: ((t: ParamOf<F>) => ParamOf<F>) =>
// @ts-expect-error not sure
pipe(
// @ts-expect-error not sure
pairRight(condition),
([value, passed]) => {
([value, passed]: [ParamOf<F>, boolean]) => {
if (!passed) throw new Error(errorMessage);
return value;
},
Expand Down

0 comments on commit dea73c3

Please sign in to comment.