Skip to content
This repository has been archived by the owner on Dec 1, 2017. It is now read-only.

Commit

Permalink
Merge pull request #6 from cassiozen/master
Browse files Browse the repository at this point in the history
Bind partial arguments
  • Loading branch information
jtarchie committed Jan 19, 2013
2 parents 8960c69 + 51d9e74 commit 33d9dec
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 7 deletions.
13 changes: 9 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -616,15 +616,20 @@ end)

## bind

`_.bind(function, table)`
`_.bind(function, table, [arguments])`

Bind a function to a table, meaning that whenever the function is called, the value of self will be the table.
Bind a function to a table, meaning that whenever the function is called, the value of self will be the table. Optionally, bind arguments to the function to pre-fill them, also known as partial application.

```lua
local func = function(self, greeting) return greeting .. ': ' .. self.name end
func = _.bind(func, {name = 'moe'})
local greet = function(self, greeting) return greeting .. ': ' .. self.name end

func = _.bind(greet, {name = 'moe'})
func('hi')
=> 'hi: moe'

func = _.bind(greet, {name = 'moe'}, 'hey')
func()
=> 'hey: moe'
```


Expand Down
5 changes: 3 additions & 2 deletions lib/underscore.lua
Original file line number Diff line number Diff line change
Expand Up @@ -418,9 +418,10 @@ function _.after(times, func)
end
end

function _.bind(func, object)
function _.bind(func, context, ...)
local arguments = unpack({...})
return function(...)
return func(object, ...)
return func(context, unpack(_.concat(arguments,arg)))
end
end

Expand Down
7 changes: 6 additions & 1 deletion spec/functions_spec.lua
Original file line number Diff line number Diff line change
Expand Up @@ -58,9 +58,14 @@ end)

describe("#bind", function()
local table = {name = "moe"}
local greet = function(self) return "hi: " .. self.name end
local greet = function(self, greeting) return greeting .. ": " .. self.name end
it("returns a closure that binds a function to a table scope ", function()
local binded = _.bind(greet, table)
assert.equals(binded("hi"), "hi: moe")
end)

it("creates a partial application by pre-filling arguments", function()
local binded = _.bind(greet, table, "hi")
assert.equals(binded(), "hi: moe")
end)
end)
Expand Down

0 comments on commit 33d9dec

Please sign in to comment.