sweet-monads
sweet-monads copied to clipboard
Proposal: Convinience methods for containers
In js you can override object properties with symbols. TS can add very good type safety for this
as well.
Example for Maybe
class Maybe<T, State> {
// If current value is Just and is iterable allow to iterate without unwrapping
*[Symbol.iterator]<T>(this: MaybeConstructor<Iterable<T>, MaybeState.Just>) {
if(this.isLeft() || !(Symbol.iterator in this.value)) return; // or throw
yield* this.value;
}
// [object Object] => [object Maybe]
get [Symbol.toStringTag]() {
return this.constructor.name;
}
}
What else is possible & easy to add
-
valueOf()
for auto unwrapping primitives in old JS -
toString()
(overridesSymbol.toStringTag
) -
[Symbol.toPrimitive]
(modern auto unwrapping for primitives) -
[Symbol.asyncIterator]