Skip to content

Commit

Permalink
Added callback argument support to utils.array.sum;
Browse files Browse the repository at this point in the history
  • Loading branch information
fabiocaccamo committed Sep 30, 2021
1 parent 8345c9d commit 3562935
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 1 deletion.
5 changes: 4 additions & 1 deletion src/utils/ArrayUtil.js
Original file line number Diff line number Diff line change
Expand Up @@ -242,8 +242,11 @@ ArrayUtil = {
return list.sort(compare);
},

sum: function(list) {
sum: function(list, callback) {
return ArrayUtil.reduce(list, function(a, b) {
if (TypeUtil.isFunction(callback)) {
return (a + callback(b));
}
return (a + b);
}, 0);
},
Expand Down
6 changes: 6 additions & 0 deletions test/test_array.js
Original file line number Diff line number Diff line change
Expand Up @@ -729,6 +729,12 @@ describe('array', function() {
a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
test.assertEqual(f(a), 45);
});
it('test array of objects', function() {
a = [{ n:0 }, { n:1 }, { n:2 }, { n:3 }, { n:4 }, { n:5 }, { n:6 }, { n:7 }, { n:8 }, { n:9 }];
test.assertEqual(f(a, function(item) {
return item['n'];
}), 45);
});
});
describe('unique', function() {
var f = arr.unique;
Expand Down

0 comments on commit 3562935

Please sign in to comment.