DEV Community

Calin Baenen
Calin Baenen

Posted on

3 2

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.)

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

SurveyJS custom survey software

Build Your Own Forms without Manual Coding

SurveyJS UI libraries let you build a JSON-based form management system that integrates with any backend, giving you full control over your data with no user limits. Includes support for custom question types, skip logic, an integrated CSS editor, PDF export, real-time analytics, and more.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay