mirror of
https://github.com/whoisclebs/lodash.git
synced 2026-01-29 06:27:49 +00:00
Fix reduceRight() so that if you don't pass in an initial value, the last item in the collection is used
This commit is contained in:
@@ -68,8 +68,14 @@ $(document).ready(function() {
|
||||
});
|
||||
|
||||
test('collections: reduceRight', function() {
|
||||
var list = _.foldr([1, 2, 3], function(memo, num){ return memo + num; }, '');
|
||||
equals(list, '321', 'can perform right folds');
|
||||
var list = _.reduceRight(["foo", "bar", "baz"], function(memo, str){ return memo + str; }, '');
|
||||
equals(list, 'bazbarfoo', 'can perform right folds');
|
||||
|
||||
var list = _.foldr(["foo", "bar", "baz"], function(memo, str){ return memo + str; }, '');
|
||||
equals(list, 'bazbarfoo', 'aliased as "foldr"');
|
||||
|
||||
var list = _.foldr(["foo", "bar", "baz"], function(memo, str){ return memo + str; });
|
||||
equals(list, 'bazbarfoo', 'default initial value');
|
||||
});
|
||||
|
||||
test('collections: detect', function() {
|
||||
|
||||
@@ -107,7 +107,9 @@
|
||||
_.reduceRight = _.foldr = function(obj, iterator, memo, context) {
|
||||
if (nativeReduceRight && obj.reduceRight === nativeReduceRight) {
|
||||
if (context) iterator = _.bind(iterator, context);
|
||||
return obj.reduceRight(iterator, memo);
|
||||
var args = [iterator];
|
||||
if (memo !== undefined) args.push(memo);
|
||||
return obj.reduceRight.apply(obj, args);
|
||||
}
|
||||
var reversed = (_.isArray(obj) ? obj.slice() : _.toArray(obj)).reverse();
|
||||
return _.reduce(reversed, iterator, memo, context);
|
||||
|
||||
Reference in New Issue
Block a user