Skip to content

Instantly share code, notes, and snippets.

@NullEntity
Created February 19, 2016 15:32
Show Gist options
  • Save NullEntity/33919d8fa65477423269 to your computer and use it in GitHub Desktop.
Save NullEntity/33919d8fa65477423269 to your computer and use it in GitHub Desktop.
private readonly Dictionary<object, Dictionary<Type, Dictionary<object, object>>> _memos = new Dictionary<object, Dictionary<Type, Dictionary<object, object>>>();
public TOut Memoize<TIn, TOut>(TIn input, Func<TIn, TOut> expression)
{
if (_memos.ContainsKey(input)
&& _memos[input].ContainsKey(typeof (TIn))
&& _memos[input][typeof (TIn)].ContainsKey(expression))
return (TOut) _memos[input][typeof (TIn)][expression];
var result = expression(input);
if (!_memos.ContainsKey(input))
_memos[input] = new Dictionary<Type, Dictionary<object, object>>();
if (!_memos[input].ContainsKey(typeof (TIn)))
_memos[input][typeof (TIn)] = new Dictionary<object, object>();
_memos[input][typeof (TIn)][expression] = result;
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment