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

com.koushikdutta.quack.Memoize Maven / Gradle / Ivy

There is a newer version: 1.1.0
Show newest version
package com.koushikdutta.quack;

import java.util.HashMap;

public class Memoize {
  public interface MemoizeMap {
    boolean containsKey(Object key);
    V get(Object key);
    V put(Integer key, V value);
    void clear();
  }

  private static class MemoizeMapImpl extends HashMap implements MemoizeMap {
    /**
     *
     */
    private static final long serialVersionUID = -4020434697394716201L;
  }

  public Memoize(MemoizeMap map) {
    store = map;
  }
  public Memoize() {
    this(new MemoizeMapImpl<>());
  }

  public static int hashCode(Object... objects) {
    int ret = 0;
    for (int i = 0; i < objects.length; i++) {
      Object o = objects[i];
      ret ^= Integer.rotateLeft(o == null ? 0 : o.hashCode(), i);
    }
    ret ^= objects.length;
    return ret;
  }

  MemoizeMap store;
  public T memoize(MemoizeFunc func, Object... args) {
    int hash = hashCode(args);
    return memoize(func, hash);
  }

  void clear() {
    store.clear();
  }

  public T memoize(MemoizeFunc func, Object arg0, Object[] args) {
    int hash = hashCode(args);
    hash ^= arg0 == null ? 0 : arg0.hashCode();
    return memoize(func, hash);
  }

  public T memoize(MemoizeFunc func, Object arg0, Object[] args0, Object[] args1) {
    int hash = hashCode(args0);
    hash ^= hashCode(args1);
    hash ^= arg0 == null ? 0 : arg0.hashCode();
    return memoize(func, hash);
  }

  private T memoize(MemoizeFunc func, int hash) {
    if (store.containsKey(hash)) {
      return store.get(hash);
    }
    T ret = func.process();
    store.put(hash, ret);
    return ret;
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy