Skip to content

Commit 6ce2557

Browse files
Add support for arrow functions to reduce filter.
1 parent b656062 commit 6ce2557

File tree

2 files changed

+26
-0
lines changed

2 files changed

+26
-0
lines changed

src/twig.filters.js

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -869,6 +869,20 @@ module.exports = function (Twig) {
869869
});
870870
return newValue;
871871
}
872+
},
873+
reduce(value, params) {
874+
if (is('Array', value)) {
875+
const callBackParams = params.params.split(',');
876+
return value.reduce((_carry, _v, _k) => {
877+
const data = {};
878+
data[callBackParams[0]] = _carry;
879+
data[callBackParams[1].trim()] = _v;
880+
data[callBackParams[2].trim()] = _k;
881+
882+
const template = Twig.exports.twig({data: params.body});
883+
return template.render(data);
884+
}, params.args || 0);
885+
}
872886
}
873887
};
874888

test/test.filters.js

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -887,6 +887,18 @@ describe('Twig.js Filters ->', function () {
887887
});
888888
});
889889

890+
describe('reduce ->', function () {
891+
it('should reduce an array (with inital value)', function () {
892+
let testTemplate = twig({data: '{{ [1,2,3]|reduce((carry, v, k) => carry + v * k) }}'});
893+
testTemplate.render().should.equal('8');
894+
});
895+
896+
it('should reduce an array)', function () {
897+
let testTemplate = twig({data: '{{ [1,2,3]|reduce((carry, v, k) => carry + v * k, 10) }}'});
898+
testTemplate.render().should.equal('18');
899+
});
900+
});
901+
890902
it('should chain', function () {
891903
const testTemplate = twig({data: '{{ ["a", "b", "c"]|keys|reverse }}'});
892904
testTemplate.render().should.equal('2,1,0');

0 commit comments

Comments
 (0)