SHOW:
|
|
- or go back to the newest paste.
| 1 | import * as Task from "fp-ts/Task"; | |
| 2 | import * as TaskEither from "fp-ts/TaskEither"; | |
| 3 | import * as ReadonlyArray from "fp-ts/ReadonlyArray"; | |
| 4 | - | import { pipe, identity } from "fp-ts/function";
|
| 4 | + | import { pipe } from "fp-ts/function";
|
| 5 | ||
| 6 | const example = async () => {
| |
| 7 | const getUserPreferences = ( | |
| 8 | userId: string | |
| 9 | ): TaskEither.TaskEither<string, string> => {
| |
| 10 | if (userId.includes("invalid")) {
| |
| 11 | return TaskEither.left("No preferences found");
| |
| 12 | } | |
| 13 | return TaskEither.right(userId); | |
| 14 | }; | |
| 15 | ||
| 16 | const userIds = ["a", "b", "c"]; | |
| 17 | ||
| 18 | - | const mapTaskEither = ReadonlyArray.traverse(TaskEither.ApplicativeSeq)( |
| 18 | + | const mapTaskEither = TaskEither.traverseArray( |
| 19 | getUserPreferences | |
| 20 | ); | |
| 21 | const result = await mapTaskEither(userIds)(); | |
| 22 | console.log(`Result: ${JSON.stringify(result)}`);
| |
| 23 | ||
| 24 | const validAndInvalidUserIds = ["a", "invalid", "c"]; | |
| 25 | const anotherResult = await mapTaskEither(validAndInvalidUserIds)(); | |
| 26 | console.log( | |
| 27 | `If there's at least one Left, the whole result is a Left: ${JSON.stringify(
| |
| 28 | anotherResult | |
| 29 | )}` | |
| 30 | ); | |
| 31 | ||
| 32 | const onlyRightResults = await pipe( | |
| 33 | validAndInvalidUserIds, | |
| 34 | - | ReadonlyArray.traverse(Task.ApplicativeSeq)(getUserPreferences), |
| 34 | + | Task.traverseArray(getUserPreferences), |
| 35 | - | Task.map(ReadonlyArray.partitionMap(identity)), |
| 35 | + | Task.map(ReadonlyArray.separate), |
| 36 | Task.map(({ right }) => right)
| |
| 37 | )(); | |
| 38 | console.log( | |
| 39 | `Updated function to get all Right results: ${JSON.stringify(
| |
| 40 | onlyRightResults | |
| 41 | )}` | |
| 42 | ); | |
| 43 | }; | |
| 44 | ||
| 45 | - | example(); |
| 45 | + | example(); |