fp-tsとneverthrow
めちゃくちゃ表面しか見ていないmrsekut.icon
fp-tsはTypeScriptでfpをやるlibrary
monadなどの抽象化も用意されている
neverthrowは、Either限定で提供しているlibrary
fp-tsと異なり、method chainで書ける
同じコードを書く
両方ともmonadを使っていることに変わりはないので、ほぼ同じ書き味ではある
code:fp-ts.ts
import * as E from "fp-ts/lib/Either";
import { pipe } from "fp-ts/lib/function";
function itsUnder100(n: number) {
return n <= 100 ? E.right(n) : E.left(new Error("Number is over 100"));
}
function itsEven(n: number) {
return n % 2 === 0 ? E.right(n) : E.left(new Error("Number is odd"));
}
function itsPositive(n: number) {
return n >= 0 ? E.right(n) : E.left(new Error("Number is negative"));
}
const result = pipe(
E.right(96),
E.chain(itsUnder100),
E.chain(itsPositive),
E.chain(itsEven),
E.match(
(e) => console.log(e.message),
(n) => console.log(n)
)
);
code:neverthrow.ts
import { Result, ok, err } from "neverthrow";
function itsUnder100(n: number): Result<number, Error> {
return n <= 100 ? ok(n) : err(new Error("Number is over 100"));
}
function itsEven(n: number): Result<number, Error> {
return n % 2 === 0 ? ok(n) : err(new Error("Number is odd"));
}
function itsPositive(n: number): Result<number, Error> {
return n >= 0 ? ok(n) : err(new Error("Number is negative"));
}
const result = ok(96)
.andThen(itsUnder100)
.andThen(itsEven)
.andThen(itsPositive)
.match(
(n) => console.log(n),
(e) => console.log(e.message)
);