ООП в JavaScriptКлассыmedium

Optional

Реализуйте класс Optional для оборачивания ненулевых значений. Такой класс есть в языке Java (подробное описание).

const opt1 = Optional.of(5); const opt2 = Optional.empty(); function double(opt) { return opt.map(x => x * 2); } console.log(double(opt1).get()); // 10 console.log(double(opt2).isPresent()); // false

Зачем такой класс нужен?

Например, у нас есть список разработчиков, среди которых должен быть ментейнер (основной разработчик, отвечающий за проект). Но ментейнера может и не оказаться. Задача: вывести имя ментейнера, если он есть.

const users = [{ name: "Max", role: "maintainer" }, { name: "Dan", role: "dev" }]; // надо вывести "Max"

Сейчас, с использованием optional chaining, мы можем написать так:

const users = [{ name: "Max", role: "maintainer" }, { name: "Dan", role: "dev" }]; const name = users.find(user => user.role === "maintainer")?.name; if (name !== undefined) { console.log(name); }

Но когда-то в джаваскрипте не было optional chaining. И история могла пойти иначе. Если бы find возвращал Optional вместо значения или undefined, мы могли бы писать как в джаве:

Array.prototype.optionalFind = function(predicate) { for(const element of this) { if (predicate(element)) { return Optional.of(element); } } return Optional.empty(); } const users = [{ name: "Max", role: "maintainer" }, { name: "Dan", role: "dev" }]; users .optionalFind(user => user.role === "maintainer") .map(user => user.name) .ifPresent(name => console.log(name));

Методы класса

  • filter(predicate) - If a value is present, and the value matches the given predicate, return an Optional describing the value, otherwise return an empty Optional.
  • flatMap(mapper) - If a value is present, apply the provided Optional-bearing mapping function to it, return that result, otherwise return an empty Optional.
  • get() - If a value is present in this Optional, returns the value, otherwise throws NoSuchElementException.
  • ifPresent(consumer) - If a value is present, invoke the specified consumer with the value, otherwise do nothing.
  • isPresent() - Return true if there is a value present, otherwise false.
  • map(mapper) - If a value is present, apply the provided mapping function to it, and if the result is non-null, return an Optional describing the result.
  • equals(obj) - Indicates whether some other object is "equal to" this Optional.
  • orElse(other) - Return the value if present, otherwise return other.
  • orElseGet(supplier) - Return the value if present, otherwise invoke other and return the result of that invocation.
  • orElseThrow(exceptionSupplier) - Return the contained value, if present, otherwise throw an exception to be created by the provided supplier.
  • toString() - Returns a non-empty string representation of this Optional suitable for debugging. Например, для Optional.of(5) возвращается строка "Optional[5]", для Optional.empty() возвращается строка "Optional.empty".

Статические методы класса

  • empty() - Returns an empty Optional instance.
  • of(value) - Returns an Optional with the specified present non-null value.
  • ofNullable(value) - Returns an Optional describing the specified value, if non-null, otherwise returns an empty Optional.