maybe.ts 842 B

12345678910111213141516171819202122232425262728293031323334353637
  1. /**
  2. *
  3. * Maybe Monad
  4. * @Source: https://codewithstyle.info/advanced-functional-programming-in-typescript-maybe-monad/
  5. * @Modified by: @lucascalion - 28/08/2019
  6. *
  7. **/
  8. export class Maybe<T> {
  9. private constructor(private value: T | null) {}
  10. static some<T> (value: T): Maybe<T> {
  11. if (!value) {
  12. throw Error("Provided value must not be empty");
  13. }
  14. return new Maybe(value);
  15. }
  16. static none<T> (): Maybe<T> {
  17. return new Maybe<T>(null);
  18. }
  19. static fromValue<T> (value: T): Maybe<T> {
  20. return value ? Maybe.some(value) : Maybe.none<T>();
  21. }
  22. getOrElse(defaultValue: T): T {
  23. return this.value === null ? defaultValue : this.value;
  24. }
  25. map<R>(f: (wrapped: T) => R): Maybe<R> {
  26. if (this.value === null) {
  27. return Maybe.none<R>();
  28. } else {
  29. return Maybe.fromValue(f(this.value));
  30. }
  31. }
  32. }