Skip to content

Commit

Permalink
Add support for arrow functions to reduce filter.
Browse files Browse the repository at this point in the history
  • Loading branch information
antoineveldhoven committed Sep 27, 2023
1 parent 1f81225 commit ee22d77
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 0 deletions.
14 changes: 14 additions & 0 deletions src/twig.filters.js
Original file line number Diff line number Diff line change
Expand Up @@ -865,6 +865,20 @@ module.exports = function (Twig) {
});
return newValue;
}
},
reduce(value, params) {
if (is('Array', value)) {
const callBackParams = params.params.split(',');
return value.reduce((_carry, _v, _k) => {
const data = {};
data[callBackParams[0]] = _carry;
data[callBackParams[1].trim()] = _v;
data[callBackParams[2].trim()] = _k;

const template = Twig.exports.twig({data: params.body});
return template.render(data);
}, params.args || 0);
}
}
};

Expand Down
12 changes: 12 additions & 0 deletions test/test.filters.js
Original file line number Diff line number Diff line change
Expand Up @@ -883,6 +883,18 @@ describe('Twig.js Filters ->', function () {
});
});

describe('reduce ->', function () {
it('should reduce an array (with inital value)', function () {
let testTemplate = twig({data: '{{ [1,2,3]|reduce((carry, v, k) => carry + v * k) }}'});
testTemplate.render().should.equal('8');
});

it('should reduce an array)', function () {
let testTemplate = twig({data: '{{ [1,2,3]|reduce((carry, v, k) => carry + v * k, 10) }}'});
testTemplate.render().should.equal('18');
});
});

it('should chain', function () {
const testTemplate = twig({data: '{{ ["a", "b", "c"]|keys|reverse }}'});
testTemplate.render().should.equal('2,1,0');
Expand Down

0 comments on commit ee22d77

Please sign in to comment.