Skip to content

Commit

Permalink
Add Function: withLet (#68)
Browse files Browse the repository at this point in the history
  • Loading branch information
erwijet authored Oct 10, 2023
1 parent 990a5b8 commit ec8b982
Show file tree
Hide file tree
Showing 4 changed files with 35 additions and 3 deletions.
5 changes: 5 additions & 0 deletions .changeset/curvy-files-heal.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@bryx-inc/ts-utils": minor
---

Introduce `withLet` function
6 changes: 5 additions & 1 deletion src/function.test.ts
Original file line number Diff line number Diff line change
@@ -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", () => {
Expand Down Expand Up @@ -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);
});
24 changes: 24 additions & 0 deletions src/function.ts
Original file line number Diff line number Diff line change
Expand Up @@ -147,3 +147,27 @@ export function inject<T>(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<T, E = T>(val: T, fn: (it: T) => E): E {
return fn(val);
}
3 changes: 1 addition & 2 deletions src/object.ts
Original file line number Diff line number Diff line change
@@ -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 */
Expand Down

0 comments on commit ec8b982

Please sign in to comment.