From d8d7c93356993bc068e8b42f61d6ac26d85d703f Mon Sep 17 00:00:00 2001 From: Marcus Irven Date: Sun, 13 Dec 2009 12:33:35 -0600 Subject: [PATCH] add _.range --- lib/underscore.lua | 14 +++++++++++++ spec/range_spec.lua | 50 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 64 insertions(+) create mode 100644 spec/range_spec.lua diff --git a/lib/underscore.lua b/lib/underscore.lua index 6cc68b3..37142e8 100644 --- a/lib/underscore.lua +++ b/lib/underscore.lua @@ -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 diff --git a/spec/range_spec.lua b/spec/range_spec.lua new file mode 100644 index 0000000..a4b3c8c --- /dev/null +++ b/spec/range_spec.lua @@ -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)