supermacro / neverthrow

Type-Safe Errors for JS & TypeScript
MIT License
4.03k stars 84 forks source link

feat: Add a function that combines multiple results and returns an object #610

Open Karibash opened 1 week ago

Karibash commented 1 week ago

Hi @supermacro ,

First of all, I would like to thank you for creating such a wonderful library. I have been using neverthrow in a production environment for about a year and I am very satisfied with it.

In this PR, I am adding a function that combines multiple Results, passed as an object, into a single Result. This can be very useful for functional programming as shown below:

const createTaskId: (id: string) => Result<TaskId, Error>;
const createTaskContent: (content: string) => Result<TaskContent, Error>;

const task = Result.struct({
  id: createTaskId('id'),
  content: createTaskContent('content'),
});

To do the same thing with the current API, you need to use map as shown below. This requires you to remember which data is in which position in the array, which is not very convenient.

const createTaskId: (id: string) => Result<TaskId, Error>;
const createTaskContent: (content: string) => Result<TaskContent, Error>;

const values = Result.combineWithAllErrors([
  createTaskId('id'),
  createTaskContent('content'),
]);

const task = values.map(([id, content]) => ({ id, content }));
changeset-bot[bot] commented 1 week ago

🦋 Changeset detected

Latest commit: 595c76aca2b3fde9788057287ce5ab2058d491e9

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 1 package | Name | Type | | ---------- | ----- | | neverthrow | Minor |

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR