diff --git a/docs/index.html b/docs/index.html index d6c022b..fbb8593 100644 --- a/docs/index.html +++ b/docs/index.html @@ -20,6 +20,9 @@
Produces a new array by mapping each value in iter through a transformation function.
_.map({1,2,3}, function(i) return i*2 end) => { 2,4,6 }+
+ combine
+ _.combine(iters, func)
+
Produces a new array by mapping each value in each array in iters through a transformation function.
+_.combine({ {1,2,3}, {3,2,1}, {1,1,1} }, function(a,b,c) a+b+c end) => { 5,5,5 } _.combine({ {3,2,1}, {1,1,1,1,1} }, function(a,b) a+b end) => { 4,3,2 }+
each diff --git a/lib/underscore.lua b/lib/underscore.lua index 7415190..e4bb939 100644 --- a/lib/underscore.lua +++ b/lib/underscore.lua @@ -97,6 +97,18 @@ function Underscore.funcs.map(list, func) return mapped end +function Underscore.funcs.combine(list, func) + local mapped = {} + local remaining_lists = _.map(_.rest(list), Underscore.iter) + for v1 in Underscore.iter(list[1]) do + local remaining_vals = _.map(remaining_lists, function (x) + return x() + end) + mapped[#mapped+1] = func(v1, unpack(remaining_vals)) + end + return mapped +end + function Underscore.funcs.reduce(list, memo, func) for i in Underscore.iter(list) do memo = func(memo, i) diff --git a/spec/combine_spec.lua b/spec/combine_spec.lua new file mode 100644 index 0000000..29b5ade --- /dev/null +++ b/spec/combine_spec.lua @@ -0,0 +1,15 @@ +require 'spec_helper' + +describe["_.combine"] = function() + before = function() + input = { {1,2,3}, {3,2,1,0}, {1,1,1,1,1} } + result = _.combine(input, function(a,b,c) return a+b+c end) + end + + it["should return an array of size of the first array with the elements of all arrays transformed by the function"] = function() + expect(result).should_equal {5,5,5} + end +end + + +spec:report(true) diff --git a/template/functions.yaml b/template/functions.yaml index 0a504dc..38142c7 100644 --- a/template/functions.yaml +++ b/template/functions.yaml @@ -13,6 +13,18 @@ iterator_functions: _.map({1,2,3}, function(i) return i*2 end) => { 2,4,6 } + - name: + combine + params: + iters, func + description: + Produces a new array by mapping each value in each array in iters through a transformation function. + example: | + _.combine({ {1,2,3}, {3,2,1}, {1,1,1} }, function(a,b,c) a+b+c end) + => { 5,5,5 } + _.combine({ {3,2,1}, {1,1,1,1,1} }, function(a,b) a+b end) + => { 4,3,2 } + - name: each aliases: