Skip to content

Instantly share code, notes, and snippets.

@tusharmath
Created April 20, 2015 16:15
Show Gist options
  • Save tusharmath/98f049885a585d26c8fe to your computer and use it in GitHub Desktop.
Save tusharmath/98f049885a585d26c8fe to your computer and use it in GitHub Desktop.
Chaining API
Q = require 'q'
chai = require 'chai'
.should()
chain = (proto) ->
obj =
_value: null
value: -> @_value
for k, v of proto
obj[k] = chain._actionCreate proto, obj, k, v
obj
chain._actionCreate = (proto, obj, k, v) ->
(args...) ->
args.unshift obj._value
obj._value = v.apply proto, args
obj
describe "Chain", ->
it "chain is a function", ->
chain.should.be.a 'function'
it 'returns value of the obj', ->
proto =
a: -> 100
chain proto
.a()
.value().should.equal 100
it 'returns value of the obj with multiple actions', ->
proto =
a: -> 100
b: (value) -> value + 200
chain proto
.a().b()
.value().should.equal 300
it 'handles custom parameters to the action', ->
proto =
a: -> 100
b: (value = 0, custom = 0) ->value + 200 + custom
chain proto
.a().b(500)
.value().should.equal 800
it "experiement", ->
proto =
a: -> 100
b: (value, custom = 0) ->
value + 200 + custom
x = chain proto
.a().b(500)
x.b()
x.b()
x.value().should.equal 1200
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment