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

at.chrl.nutils.Memoizer Maven / Gradle / Ivy

The newest version!
/**
 * This file is part of ChRL Util Collection.
 * 
 * ChRL Util Collection is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by the Free
 * Software Foundation, either version 3 of the License, or (at your option) any
 * later version.
 * 
 * ChRL Util Collection is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 * 
 * You should have received a copy of the GNU General Public License along with
 * ChRL Util Collection. If not, see .
 */
package at.chrl.nutils;

import java.util.Map;
import java.util.function.Function;
import java.util.function.Predicate;

/**
 * @author Vinzynth 08.11.2014 - 16:39:32
 * 
 * @see http://java.dzone.com/articles/java-8-automatic-memoization
 */
public class Memoizer {

	/**
	 * No lambda expressions here, since Javaagent does not support that yet
	 * 
	 * @param function
	 * @return
	 */
	private static  Function doMemoize(final Function function) {
		Map cache = CollectionUtils.newMap();
		return new Function() {
			@Override
			public U apply(T t) {
				return cache.computeIfAbsent(t, function::apply);
			}
		};
	}
	
	/**
	 * No lambda expressions here, since Javaagent does not support that yet
	 * 
	 * @param function
	 * @return
	 */
	private static  Predicate doMemoize(final Predicate predicate) {
		Map cache = CollectionUtils.newMap();
		return new Predicate() {

			@Override
			public boolean test(T t) {
				return cache.computeIfAbsent(t, predicate::test);
			}
		};
	}

	public static  Function memoize(final Function function) {
		return doMemoize(function);
	}

	public static  Predicate memoizePredicate(final Predicate predicate) {
		return doMemoize(predicate);
	}
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy