package thyyxxk.webserver.utils;


import java.util.*;
import java.util.function.Function;


/**
 * @author xc
 */
public class CacheOnce<V> {
    private final Map<String, V> map = new HashMap<>();
    private final Set<String> notQueried = new HashSet<>();

    public CacheOnce() {

    }

    public V get(String name) {
        if (map.containsKey(name)) {
            return map.get(name);
        }
        return null;
    }

    public V get(String name, Function<String, V> filter) {
        Objects.requireNonNull(filter);

        if (map.containsKey(name)) {
            return map.get(name);
        }

        if (notQueried.contains(name)) {
            return null;
        }

        V object = filter.apply(name);

        if (object == null) {
            notQueried.add(name);
            return null;
        } else {
            map.put(name, object);
            return object;
        }
    }

}
