sweet-monads icon indicating copy to clipboard operation
sweet-monads copied to clipboard

Proposal: Identity monad

Open AlexXanderGrib opened this issue 2 years ago • 1 comments

All current monads in package are representing some extra state (Left/Right, Just/None), but using monads just for chaining is good on itself

Example:

// Before
app.use(
  express.static(
    path.resolve(getDirname(import.meta.url), "../public")
  )
)


// After
new Chain(import.meta.url)
    .map(getDirname)
    .map(path.resolve, "../public")
    .map(express.static)
    .map(app.use);

Example implementation

export class Chain<T> {
  constructor(public readonly value: T) {}

  map<X, A extends unknown[]>(
    mapper: (...parameters: [value: T, ...rest: A]) => X,
    ...rest: A
  ): Chain<X> {
    return new Chain(mapper(this.value, ...rest));
  }
}

export class AsyncChain<T> {
  constructor(public readonly value: T | PromiseLike<T>) {}

  map<X, A extends unknown[]>(
    mapper: (
      ...parameters: [value: T, ...rest: A]
    ) => X | PromiseLike<X>,
    ...rest: A
  ): AsyncChain<X> {
    return new AsyncChain(
      Promise.resolve(this.value).then((x) => mapper(x, ...rest))
    );
  }

  async get() {
    return await this.value;
  }
}

AlexXanderGrib avatar Sep 09 '22 18:09 AlexXanderGrib

Sounds really good. It looks like an Identity monad.

JSMonk avatar Sep 13 '22 12:09 JSMonk

@JSMonk how to install it? Npm is empty

numfin avatar Mar 04 '23 14:03 numfin

Hey @numfin. Sorry for the long waiting. You can install it with @sweet-monads/* workspace. For example, @sweet-monads/maybe for Maybe monad, or @sweet-monads/iterator for LazyIterator

JSMonk avatar Apr 02 '23 08:04 JSMonk

Hey @numfin. Sorry for the long waiting. You can install it with @sweet-monads/* workspace. For example, @sweet-monads/maybe for Maybe monad, or @sweet-monads/iterator for LazyIterator

Nvm i made my own lib kirka

numfin avatar Apr 02 '23 08:04 numfin