com.github.tonivade.purefun.optics.Prism Maven / Gradle / Ivy
/*
* Copyright (c) 2018-2019, 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.Producer.cons;
import static java.util.Objects.requireNonNull;
import com.github.tonivade.purefun.Function1;
import com.github.tonivade.purefun.Operator1;
import com.github.tonivade.purefun.type.Either;
import com.github.tonivade.purefun.type.Option;
public final class Prism {
private final Function1> getOption;
private final Function1 reverseGet;
private Prism(Function1> getOption, Function1 reverseGet) {
this.getOption = requireNonNull(getOption);
this.reverseGet = requireNonNull(reverseGet);
}
public static Prism of(Function1> getOption, Function1 reverseGet) {
return new Prism<>(getOption, reverseGet);
}
public Option getOption(T target) {
return getOption.apply(target);
}
public T reverseGet(R value) {
return reverseGet.apply(value);
}
public Either getOrModify(T target) {
return getOption(target).fold(cons(Either.left(target)), Either::right);
}
public Operator1 modify(Operator1 mapper) {
return target -> modifyOption(mapper).apply(target).getOrElse(target);
}
public Operator1 set(R value) {
return modify(ignore -> value);
}
public Function1> modifyOption(Operator1 mapper) {
return target -> getOption(target).map(mapper).map(reverseGet);
}
public Function1> setOption(R value) {
return modifyOption(ignore -> value);
}
public Prism compose(Prism other) {
return new Prism<>(
target -> this.getOption(target).flatMap(other::getOption),
value -> this.reverseGet(other.reverseGet(value)));
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy