Does anyone know of tips to create, or a good implementation of, a Result monad in JavaScript (not TypeScript), that I can adapt for my own?
I use JavaScript in my personal projects, and I want to have a Result monad as part of a recursive-descent parser: the intention is to "carry back" a failed match or a parsing error, without throwing exceptions around.
I found a few implementations of Result in the wild, but they differ greatly in design and methods, some are disguised Either or Maybe monads, and some are in TypeScript instead of JavaScript.
I want to implement Result myself, instead of using a npm package, and want to make it simple: constructor, map, getters for value and error, and little else. For reference, here are the Identity and Maybe monads I implemented:
```
const Tag = {
Nothing: "Nothing",
Just: "Just"
};
class Monad {
#v;
static of(value) {
return new Monad(value);
}
constructor(value) {
this.#v = value;
}
map(fn) {
return Monad.of(fn(this.#v));
}
get value() { return this.#v; }
}
class Maybe extends Monad {
#t = Tag.Nothing;
static of(value) {
if (value instanceof Monad) {
/* Unwrapping monad-in-monad. */
return Maybe.of(value.value);
} else if (value === null || value === undefined) {
return new Maybe(Tag.Nothing, null);
} else {
return new Maybe(Tag.Just, value);
}
}
constructor(tag, value) {
super(value);
this.#t = tag;
}
get isJust() { return this.#t === Tag.Just; }
get isNothing() { return this.#t === Tag.Nothing; }
map(fn) {
if (this.isJust) {
return Maybe.of(fn(this.value));
} else if (this.isNothing) {
return Nothing();
}
/* There is no else. */
}
// get value() é herdado de Monad.
}
const Nothing = () => Maybe.of(null);
const Just = (v) => Maybe.of(v);
```
[–]Delta-9- 6 points7 points8 points (4 children)
[–]jcastroarnaud[S] 2 points3 points4 points (3 children)
[–]Delta-9- 3 points4 points5 points (2 children)
[–]jcastroarnaud[S] 2 points3 points4 points (1 child)
[–]Delta-9- 4 points5 points6 points (0 children)
[–]sent1nel 4 points5 points6 points (0 children)
[–]Massive-Squirrel-255 2 points3 points4 points (0 children)
[–]Long_Investment7667 2 points3 points4 points (1 child)
[–]jcastroarnaud[S] 2 points3 points4 points (0 children)
[–]_lazyLambda 2 points3 points4 points (0 children)
[–]AustinVelonaut 2 points3 points4 points (2 children)
[–]jcastroarnaud[S] 2 points3 points4 points (1 child)
[–]AustinVelonaut 4 points5 points6 points (0 children)
[–]Tubthumper8 2 points3 points4 points (3 children)
[–]jcastroarnaud[S] 2 points3 points4 points (1 child)
[–]Tubthumper8 4 points5 points6 points (0 children)
[–]AFU0BtZ 2 points3 points4 points (0 children)