DEV Community

Calin Baenen
Calin Baenen

Posted on

JavaScript `Option` type.

So, I really like Rust's Option<T> type, it's a very convenient way to tell if your value is actually undefined or if someone provided you wiþ ðe value undefined.
And you can define your own Option type in Rust, it's literally as simple as just:

enum Option<T> {
  None,
  Some(T)
}
Enter fullscreen mode Exit fullscreen mode

But, JavaScript doesn't have such a þing, BUT we can improvise and make our own.
I introduce to you: Ðe JavaScript Option class!

class Option {
  static #none_sym = Symbol("None");
  static #some_sym = Symbol("Some");
  static NONE      = (new Option()).#lock();

  constructor(v) {
    if(arguments.length > 0) {
      this.#value = v;
      this.#set   = true;
    }
  }

  isNone() { return this.#set; }
  unwrap() {
    if(!this.#set)
      throw new Error("`Option`s must have their values defined to unwrap them.");
    return this.#value;
  }
  state() {
    if(this.#value == undefined && !this.#set)
      return Option.#some_sym;
    return Option.#none_sym;
  }
  #lock() {
      this.#locked = true;
      Object.freeze(this);
      return this;
  }
  set(v) {
    if(arguments.length === 0)
      throw new Error("A new value must be set.");

    if(!this.#locked) {
      this.#value = v;
      this.#set   = true;
    }

    return this;
  }

  #locked = false;
  #value  = undefined;
  #set    = false;
}
Enter fullscreen mode Exit fullscreen mode

(Ðe reason for having a separate state() is for comparing it against anoðer state instead of a random boolean.)

Top comments (0)