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

Proposal: Convinience methods for containers

Open AlexXanderGrib opened this issue 2 years ago • 0 comments

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() (overrides Symbol.toStringTag)
  • [Symbol.toPrimitive] (modern auto unwrapping for primitives)
  • [Symbol.asyncIterator]

AlexXanderGrib avatar Sep 15 '22 09:09 AlexXanderGrib