Commit 67e829a

mo khan <mo@mokhan.ca>
2013-12-21 00:02:11
add memoize lambda.
1 parent f8f9daf
lib/nasty/lambda_behaviours.rb
@@ -0,0 +1,7 @@
+module Nasty
+  module LambdaBehaviours
+    def memoize(lambda_method)
+      lambda { |*args| @cache ||= lambda_method.call(*args) }
+    end
+  end
+end
lib/nasty.rb
@@ -1,6 +1,7 @@
 require "nasty/command"
 require "nasty/composite_command"
 require "nasty/kernel"
+require "nasty/lambda_behaviours"
 require "nasty/version"
 
 module Nasty
spec/unit/lambda_behaviours_spec.rb
@@ -0,0 +1,15 @@
+require "spec_helper"
+
+module Nasty
+  describe LambdaBehaviours do
+    include LambdaBehaviours
+
+    it "memoizes the lambda" do
+      calculation = memoize(lambda { |x| x + rand(100) })
+      first_result = calculation.call(1)
+      calculation.call(1).should == first_result
+      calculation.call(1).should == first_result
+      calculation.call(1).should == first_result
+    end
+  end
+end