Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import * as Task from "fp-ts/Task";
- import * as TaskEither from "fp-ts/TaskEither";
- import * as ReadonlyArray from "fp-ts/ReadonlyArray";
- import { pipe } from "fp-ts/function";
- const example = async () => {
- const getUserPreferences = (
- userId: string
- ): TaskEither.TaskEither<string, string> => {
- if (userId.includes("invalid")) {
- return TaskEither.left("No preferences found");
- }
- return TaskEither.right(userId);
- };
- const userIds = ["a", "b", "c"];
- const mapTaskEither = TaskEither.traverseArray(
- getUserPreferences
- );
- const result = await mapTaskEither(userIds)();
- console.log(`Result: ${JSON.stringify(result)}`);
- const validAndInvalidUserIds = ["a", "invalid", "c"];
- const anotherResult = await mapTaskEither(validAndInvalidUserIds)();
- console.log(
- `If there's at least one Left, the whole result is a Left: ${JSON.stringify(
- anotherResult
- )}`
- );
- const onlyRightResults = await pipe(
- validAndInvalidUserIds,
- Task.traverseArray(getUserPreferences),
- Task.map(ReadonlyArray.separate),
- Task.map(({ right }) => right)
- )();
- console.log(
- `Updated function to get all Right results: ${JSON.stringify(
- onlyRightResults
- )}`
- );
- };
- example();
Add Comment
Please, Sign In to add comment