diff --git a/.changeset/curvy-files-heal.md b/.changeset/curvy-files-heal.md new file mode 100644 index 0000000..4fe9706 --- /dev/null +++ b/.changeset/curvy-files-heal.md @@ -0,0 +1,5 @@ +--- +"@bryx-inc/ts-utils": minor +--- + +Introduce `withLet` function diff --git a/src/function.test.ts b/src/function.test.ts index a1c54c0..108ba83 100644 --- a/src/function.test.ts +++ b/src/function.test.ts @@ -1,4 +1,4 @@ -import { createCurriedGuardPredicate, pipe, tryOr, inject } from "./function"; +import { createCurriedGuardPredicate, pipe, tryOr, inject, withLet } from "./function"; import { castUnsafe } from "./object"; test("create curried guard predicate", () => { @@ -50,3 +50,7 @@ test("inject", () => { expect(fn1).toHaveBeenCalledTimes(arr.length); expect(fn2).toHaveBeenCalledTimes(arr.length); }); + +test("withLet", () => { + expect(withLet(1 + 2 + 3, (it) => it + 4)).toEqual(1 + 2 + 3 + 4); +}); diff --git a/src/function.ts b/src/function.ts index a9d7aa1..ccea953 100644 --- a/src/function.ts +++ b/src/function.ts @@ -147,3 +147,27 @@ export function inject(fn: (arg: T) => unknown): (arg: T) => T { return arg; }; } + +/** + * Apply a callback function to a value and return the result. + * + * @param {T} val - The value to be passed to the callback function. + * @param {(it: T) => E} fn - The callback function that processes the value. + * @returns {E} The result of applying the callback function to the value. + * + * @example + * ```ts + * type Data = + * | { type: "gizmo" } + * | { type: "shape", sides: number }; + * + * function getData(): Data { + * // ... + * } + * + * const sides = withLet(getData(), it => it.type == "shape" ? it.sides : 0); + * ``` + */ +export function withLet(val: T, fn: (it: T) => E): E { + return fn(val); +} diff --git a/src/object.ts b/src/object.ts index 6184275..2a14db0 100644 --- a/src/object.ts +++ b/src/object.ts @@ -1,6 +1,5 @@ import { cond } from "./condition"; -import { throwError } from "./errors"; -import { isNone, Maybe } from "./maybe"; +import { Maybe } from "./maybe"; import { DeepKeyOf, DeepPick, DeepValue } from "./types"; /* eslint-disable-next-line @typescript-eslint/no-unused-vars */