Factored out memoization code into it's own module. Added test.