sweet-monads
sweet-monads copied to clipboard
Proposal: Identity monad
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;
}
}
Sounds really good. It looks like an Identity
monad.
@JSMonk how to install it? Npm is empty
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
Hey @numfin. Sorry for the long waiting. You can install it with
@sweet-monads/*
workspace. For example,@sweet-monads/maybe
forMaybe
monad, or@sweet-monads/iterator
forLazyIterator
Nvm i made my own lib kirka