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

org.codegas.commons.lang.function.FunctionUtil Maven / Gradle / Ivy

There is a newer version: 3.0.0
Show 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;
            }
        };
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy