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

Commit

Permalink
Added bind function
Browse files Browse the repository at this point in the history
  • Loading branch information
Cássio Zen committed Jan 17, 2013
1 parent 821865b commit 1c3b987
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 0 deletions.
14 changes: 14 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -614,6 +614,20 @@ _.each(notes, function(note)
end)
```

## bind

`_.bind(function, table)`

Bind a function to a table, meaning that whenever the function is called, the value of self will be the table.

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


## wrap

`_.wrap(function, wrapper)`
Expand Down
6 changes: 6 additions & 0 deletions lib/underscore.lua
Original file line number Diff line number Diff line change
Expand Up @@ -418,6 +418,12 @@ function _.after(times, func)
end
end

function _.bind(func, object)
return function(...)
return func(object, ...)
end
end

function _.wrap(func, wrapper)
return function(...)
return wrapper(func, ...)
Expand Down
9 changes: 9 additions & 0 deletions spec/functions_spec.lua
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,15 @@ describe("#after", function()
end)
end)

describe("#bind", function()
local table = {name = "moe"}
local greet = function(self) return "hi: " .. 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: moe")
end)
end)

describe("#wrap", function()
it("passes arguments ", function()
local greet = function(name) return "hi: " .. name end
Expand Down

0 comments on commit 1c3b987

Please sign in to comment.