Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Combinator helpers #14

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 29 additions & 1 deletion lib/method-combinators.coffee
Original file line number Diff line number Diff line change
Expand Up @@ -117,4 +117,32 @@ this.async = do (async = undefined) ->
callback()
async_predicate.apply(this, argv.concat(decorated_base))

async
async

# ## Combinator Helpers
this.helpers = do (helpers = {}, combinators = this, resolveFunction = undefined)->

resolveFunction = (func)->
if typeof func is "string"
helpers.my func
else
func

# Sugar to reference instance methods by name.
helpers.my =
(name)->
(args...)->
func = this[name]
func.apply this, args

# Similar to composition & threading macros
helpers.pipe =
(functions...)->
(args...)->
result = undefined
for func in functions
result = resolveFunction(func).apply this, args
args = [result]
result

helpers
34 changes: 34 additions & 0 deletions lib/method-combinators.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

60 changes: 60 additions & 0 deletions spec/method-combinators.spec.coffee
Original file line number Diff line number Diff line change
Expand Up @@ -468,3 +468,63 @@ describe "Asynchronous Method Combinators", ->
decorate(base) 'no', ->

expect(a).toEqual([])
describe "helpers", ->

describe "my", ->

it "should reference instance method", ->

addFunction = C.helpers.my "add"

repeatArg = (func)->
(firstArg)->
func.apply this, [firstArg, firstArg]

class MyClass
double:
repeatArg \
addFunction

add: (x,y)-> x + y

eg = new MyClass()
expect(eg.double 4).toBe 8

describe "pipe", ->

it "should thread functions", ->

add = (x,y)-> x + y
square = (n)-> n*n
addAndSquareFunction = C.helpers.pipe add, square

repeatArg = (func)->
(firstArg)->
func.apply this, [firstArg, firstArg]

class PipeClass
doubleAndSquare:
repeatArg \
addAndSquareFunction

eg = new PipeClass()
expect(eg.doubleAndSquare 4).toBe 64

it "should thread named methods", ->

addAndSquareFunction = C.helpers.pipe "add", "square"

repeatArg = (func)->
(firstArg)->
func.apply this, [firstArg, firstArg]

class PipeClass
doubleAndSquare:
repeatArg \
addAndSquareFunction

add: (x,y)-> x + y
square: (n)-> n*n

eg = new PipeClass()
expect(eg.doubleAndSquare 4).toBe 64