Skip to content

Commit

Permalink
Merge pull request #629 from lazopm/master
Browse files Browse the repository at this point in the history
Add "sum" filter
  • Loading branch information
carljm committed Jan 19, 2016
2 parents b45db7a + c56f6f4 commit 2d2f5dd
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
20 changes: 20 additions & 0 deletions src/filters.js
Original file line number Diff line number Diff line change
Expand Up @@ -358,6 +358,26 @@ var filters = {
return res;
},

sum: function(arr, attr, start) {
var sum = 0;

if(typeof start === 'number'){
sum += start;
}

if(attr) {
arr = lib.map(arr, function(v) {
return v[attr];
});
}

for(var i = 0; i < arr.length; i++) {
sum += arr[i];
}

return sum;
},

sort: r.makeMacro(['value', 'reverse', 'case_sensitive', 'attribute'], [], function(arr, reverse, caseSens, attr) {
// Copy it
arr = lib.map(arr, function(v) { return v; });
Expand Down
21 changes: 21 additions & 0 deletions tests/filters.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
var finish = util.finish;

describe('filter', function() {

it('abs', function(done) {
equal('{{ -3|abs }}', '3');
equal('{{ -3.456|abs }}', '3.456');
Expand Down Expand Up @@ -366,6 +367,26 @@
finish(done);
});

it('sum', function(done) {
equal('{{ items | sum }}',
{ items: [1, 2, 3] },
'6');

equal('{{ items | sum("value") }}',
{ items: [{ value: 1 },
{ value: 2 },
{ value: 3 }] },
'6');

equal('{{ items | sum("value", 10) }}',
{ items: [{ value: 1 },
{ value: 2 },
{ value: 3 }] },
'16');

finish(done);
});

it('sort', function(done) {
equal('{% for i in [3,5,2,1,4,6] | sort %}{{ i }}{% endfor %}',
'123456');
Expand Down

0 comments on commit 2d2f5dd

Please sign in to comment.