From 72da300c1b183ed29bafc41b94e4368283a1aa3e Mon Sep 17 00:00:00 2001 From: Antoine Veldhoven Date: Wed, 27 Sep 2023 12:44:03 +0200 Subject: [PATCH] Add support for arrow functions to reduce filter. --- src/twig.filters.js | 14 ++++++++++++++ test/test.filters.js | 12 ++++++++++++ 2 files changed, 26 insertions(+) diff --git a/src/twig.filters.js b/src/twig.filters.js index 4fee1026..f1b744ee 100644 --- a/src/twig.filters.js +++ b/src/twig.filters.js @@ -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); + } } }; diff --git a/test/test.filters.js b/test/test.filters.js index f2528110..74038841 100644 --- a/test/test.filters.js +++ b/test/test.filters.js @@ -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');