Skip to content

Commit

Permalink
add _.range
Browse files Browse the repository at this point in the history
  • Loading branch information
mirven committed Dec 13, 2009
1 parent 98895d3 commit d8d7c93
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 0 deletions.
14 changes: 14 additions & 0 deletions lib/underscore.lua
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,20 @@ function Underscore.iter(list_or_iter)
end)
end

function Underscore.range(start_i, end_i, step)
if end_i == nil then
end_i = start_i
start_i = 1
end
step = step or 1
local range_iter = coroutine.wrap(function()
for i=start_i, end_i, step do
coroutine.yield(i)
end
end)
return Underscore:new(range_iter)
end

--- Identity function. This function looks useless, but is used throughout Underscore as a default.
-- @name _.identity
-- @param value any object
Expand Down
50 changes: 50 additions & 0 deletions spec/range_spec.lua
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
require 'luaspec'
_ = require 'underscore'

describe["_.range"] = function()
describe["when only passing a length"] = function()
it["should iterate from 1 to the length"] = function()
result = _.range(3):to_array()
expect(#result).should_be(3)
expect(result[1]).should_be(1)
expect(result[2]).should_be(2)
expect(result[3]).should_be(3)
end
end

describe["when only passing a start and end value"] = function()
it["should iterate from start to the end inclusively"] = function()
result = _.range(2,4):to_array()
expect(#result).should_be(3)
expect(result[1]).should_be(2)
expect(result[2]).should_be(3)
expect(result[3]).should_be(4)
end
end

describe["when passing a start and end value and a step"] = function()
describe["when step is positive"] = function()
it["should iterate from start to the end inclusively incremented by step"] = function()
result = _.range(2,6,2):to_array()
expect(#result).should_be(3)
expect(result[1]).should_be(2)
expect(result[2]).should_be(4)
expect(result[3]).should_be(6)
end
end

describe["when step is negative"] = function()
it["should iterate from start to the end inclusively decremented by step"] = function()
result = _.range(6,2,-2):to_array()
expect(#result).should_be(3)
expect(result[1]).should_be(6)
expect(result[2]).should_be(4)
expect(result[3]).should_be(2)
end
end
end

end


spec:report(true)

0 comments on commit d8d7c93

Please # to comment.