Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Function: withLet #68

Merged
merged 1 commit into from
Oct 10, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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