JSMonk / sweet-monads

The library which provides useful monads, interfaces, and lazy iterators.
MIT License
343 stars 22 forks source link

Proposal: `unwrap()` custom error #50

Closed AlexXanderGrib closed 1 year ago

AlexXanderGrib commented 1 year ago

Why?

For providing more helpful messages.

Other implementations:

For Either:

unwrap(errorFactory?: (left: L) => unknown) {
  // ...
  const error = typeof errorFactory === "function" 
    ? errorFactory(this.value) 
    : new Error("Either state is Left");
  // ...
}

For Maybe:

unwrap(errorFactory?: () => unknown) {
  // ...
  const error = typeof errorFactory === "function" 
    ? errorFactory(this.value) 
    : new Error("Maybe state is None");
  // ...
}
konradekk commented 1 year ago

error factories cannot return unknown if the are to be error factories… thatʼs for sure! 😅

wookieb commented 1 year ago

@konradekk IMHO this is fine since there is not requirement in JS that only instances of Error can be thrown. Literally anything can be thrown.

konradekk commented 1 year ago

well… true! 😁 (not sure if everything should be thrown, though!)

(btw. minor issue: it seems that errorFactory signature needs an update)

AlexXanderGrib commented 1 year ago

I added this method and some other ones into my implementation. I will not create a pr, cause i think that @JSMonk can't review and merge it now

https://gist.github.com/AlexXanderGrib/cb2d1de3a729b63b95588bccbb47aa8f

JSMonk commented 1 year ago

@AlexXanderGrib I came back, so, you are welcome for the PR ^_^

JSMonk commented 1 year ago

Also, I'm thinking about this whole assert and expect story and wonder if it might be better to add an extra package for monad assertions?

wookieb commented 1 year ago

This is already done. Can we close it?

Also, I'm thinking about this whole assert and expect story and wonder if it might be better to add an extra package for monad assertions?

What that package would do?

JSMonk commented 1 year ago

Just provide the API for assertions for any monad implementation