fp-ts函數語言程式設計 - 一些小技巧
阿新 • • 發佈:2021-10-15
問:如何在pipe中實現if/else判斷null?
答:Option.fromNullable
import { pipe } from "fp-ts/function"; import * as O from "fp-ts/Option"; let obj = { state: { value: "test" } }; function calculate(input: { value: string|null }) { console.log('input'); return input?.value; } console.log( pipe( obj.state, O.fromNullable, O.map((value) => calculate(value)) ) );
問:取出Either中的成功或失敗資訊
答:Folder(或Chain),以下是Folder程式碼示例
import { either as E } from "fp-ts"; import { flow } from "fp-ts/function"; interface Person { name: string; } function ValidateName(name: string): E.Either<string, string> { return /[a-zA-z]/.test(name)? E.right(name) : E.left("invalid name") } const makeError = (message: string) => new Error(message); const makeUser = flow( ValidateName, E.map((name): Person => ({ name })), E.mapLeft(makeError) ); // (name: string) => string const main = flow( makeUser, E.fold( (error) => error.message, ({ name }) => `Hi, my name is "${name}"` ) ); console.log(main("Tom")); console.log(main("123"));