org.codegas.commons.lang.function.FunctionUtil Maven / Gradle / Ivy
The newest version!
package org.codegas.commons.lang.function;
import java.util.HashMap;
import java.util.Map;
import java.util.function.BiFunction;
import java.util.function.Function;
public final class FunctionUtil {
private FunctionUtil() {
}
public static Function memoize(Function function) {
return new Function() {
Map memoMap = new HashMap<>();
@Override
public R apply(T t) {
return memoMap.computeIfAbsent(t, key -> function.apply(t));
}
};
}
public static BiFunction memoize(BiFunction biFunction) {
return new BiFunction() {
Map> memoMap = new HashMap<>();
@Override
public R apply(T t, U u) {
return memoMap.computeIfAbsent(t, key -> new HashMap<>()).computeIfAbsent(u, key -> biFunction.apply(t, u));
}
};
}
public static > BiFunction inverseMemoize(BiFunction biFunction) {
return new BiFunction() {
Map> memoMap = new HashMap<>();
@Override
public R apply(T t1, T t2) {
R result = memoMap.computeIfAbsent(t1, key -> new HashMap<>()).computeIfAbsent(t2, key -> biFunction.apply(t1, t2));
memoMap.computeIfAbsent(t2, key -> new HashMap<>()).computeIfAbsent(t1, key -> result.invert());
return result;
}
};
}
}