From 3b4c61b9c1d550f72f342f6dbbfabbfc1b16525e Mon Sep 17 00:00:00 2001 From: nate kidwell Date: Mon, 19 Nov 2012 00:11:19 -0500 Subject: [PATCH] added branchOn combinator --- lib/method-combinators.coffee | 11 +++++++++++ lib/method-combinators.js | 16 +++++++++++++++- spec/method-combinators.spec.coffee | 17 +++++++++++++++++ 3 files changed, 43 insertions(+), 1 deletion(-) diff --git a/lib/method-combinators.coffee b/lib/method-combinators.coffee index 8f712db..12ecf94 100644 --- a/lib/method-combinators.coffee +++ b/lib/method-combinators.coffee @@ -37,6 +37,17 @@ this.provided = # ## Extras +# Allows branching between functions depending on the result of a test function + +this.branchOn = + (predicate)-> + ({failure, success})-> + -> + if predicate.apply(this, arguments) + success?.apply(this, arguments) + else + failure?.apply(this, arguments) + # If the method thows an error, retry it again a certain number of times. # e.g. `retry(3) -> # doSomething as many as four times` this.retry = diff --git a/lib/method-combinators.js b/lib/method-combinators.js index 74b0d8f..119be2b 100644 --- a/lib/method-combinators.js +++ b/lib/method-combinators.js @@ -1,4 +1,4 @@ -// Generated by CoffeeScript 1.3.1 +// Generated by CoffeeScript 1.4.0 (function() { var __slice = [].slice; @@ -47,6 +47,20 @@ }; }; + this.branchOn = function(predicate) { + return function(_arg) { + var failure, success; + failure = _arg.failure, success = _arg.success; + return function() { + if (predicate.apply(this, arguments)) { + return success != null ? success.apply(this, arguments) : void 0; + } else { + return failure != null ? failure.apply(this, arguments) : void 0; + } + }; + }; + }; + this.retry = function(times) { return function(base) { return function() { diff --git a/spec/method-combinators.spec.coffee b/spec/method-combinators.spec.coffee index 17d0221..e418f22 100644 --- a/spec/method-combinators.spec.coffee +++ b/spec/method-combinators.spec.coffee @@ -168,6 +168,23 @@ describe "Method Combinators", -> expect(eg.foo).toBe('foo') + describe "branchOn", -> + + it "runs success/fail function on resulting test", -> + + decorator = C.branchOn (value)-> + value + + class BranchOnClazz + getValue: + decorator + success: -> "success" + failure: -> "failure" + + eg = new BranchOnClazz() + expect(eg.getValue(true)).toBe('success') + expect(eg.getValue(false)).toBe('failure') + describe "retry", -> describe 'times < 0', ->