Skip to content

Commit ee22d77

Browse files
Add support for arrow functions to reduce filter.
1 parent 1f81225 commit ee22d77

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
@@ -865,6 +865,20 @@ module.exports = function (Twig) {
865865
});
866866
return newValue;
867867
}
868+
},
869+
reduce(value, params) {
870+
if (is('Array', value)) {
871+
const callBackParams = params.params.split(',');
872+
return value.reduce((_carry, _v, _k) => {
873+
const data = {};
874+
data[callBackParams[0]] = _carry;
875+
data[callBackParams[1].trim()] = _v;
876+
data[callBackParams[2].trim()] = _k;
877+
878+
const template = Twig.exports.twig({data: params.body});
879+
return template.render(data);
880+
}, params.args || 0);
881+
}
868882
}
869883
};
870884

test/test.filters.js

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

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

0 commit comments

Comments
 (0)