All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.github.tonivade.purefun.optics.Prism Maven / Gradle / Ivy

The newest version!
/*
 * Copyright (c) 2018-2024, Antonio Gabriel Muñoz Conejo 
 * Distributed under the terms of the MIT License
 */
package com.github.tonivade.purefun.optics;

import static com.github.tonivade.purefun.core.Precondition.checkNonNull;
import static com.github.tonivade.purefun.core.Producer.cons;

import com.github.tonivade.purefun.core.Function1;
import com.github.tonivade.purefun.core.Operator1;
import com.github.tonivade.purefun.type.Either;
import com.github.tonivade.purefun.type.Option;

public final class Prism {

  private final PPrism delegate;

  Prism(PPrism delegate) {
    this.delegate = checkNonNull(delegate);
  }

  public static  Prism of(Function1> getOption, Function1 reverseGet) {
    return new Prism<>(PPrism.of(
        target -> getOption.apply(target).fold(cons(Either.left(target)), Either::right), reverseGet));
  }

  public Option getOption(S target) {
    return delegate.getOption(target);
  }

  public S reverseGet(A value) {
    return delegate.reverseGet(value);
  }

  public Either getOrModify(S target) {
    return delegate.getOrModify(target);
  }

  public Operator1 modify(Operator1 mapper) {
    return delegate.modify(mapper)::apply;
  }

  public S modify(S target, Operator1 mapper) {
    return delegate.modify(target, mapper);
  }

  public Operator1 set(A value) {
    return delegate.set(value)::apply;
  }

  public S set(S target, A value) {
    return delegate.set(target, value);
  }

  public Function1> modifyOption(Operator1 mapper) {
    return delegate.modifyOption(mapper);
  }

  public Function1> setOption(A value) {
    return delegate.setOption(value);
  }

  public Optional asOptional() {
    return new Optional<>(delegate.asOptional());
  }

  public  Prism compose(Prism other) {
    return new Prism<>(delegate.compose(other.delegate));
  }

  public  Optional compose(Optional other) {
    return asOptional().compose(other);
  }

  public  Prism compose(Iso other) {
    return compose(other.asPrism());
  }

  public  Optional compose(Lens other) {
    return asOptional().compose(other);
  }
}