Skip to content

Commit

Permalink
Add support for arrow functions to map filter.
Browse files Browse the repository at this point in the history
  • Loading branch information
antoineveldhoven committed Nov 17, 2023
1 parent 95ba3c2 commit b656062
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
19 changes: 19 additions & 0 deletions src/twig.filters.js
Original file line number Diff line number Diff line change
Expand Up @@ -850,6 +850,25 @@ module.exports = function (Twig) {
return template.render(data) === 'true';
});
}
},
map(value, params) {
if (is('Array', value)) {
const callBackParams = params.params.split(',');
// Since Javascript does not support a callBack function to map() with both keys and values; we use forEach here
// Note: Twig and PHP use ((value[, key])) for map(); whereas Javascript uses (([key, ]value)) for forEach()
const newValue = [];
value.forEach((_b, _a) => {
const data = {};
data[callBackParams[0].trim()] = _b;
if (callBackParams[1]) {
data[callBackParams[1].trim()] = _a;
}

const template = Twig.exports.twig({data: params.body});
newValue[_a] = template.render(data);
});
return newValue;
}
}
};

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

describe('map ->', function () {
it('should map an array (with keys)', function () {
let testTemplate = twig({data: '{{ [1,5,2,7,8]|map((v, k) => v*v+k) }}'});
testTemplate.render().should.equal('1,26,6,52,68');
});

it('should map an array', function () {
let testTemplate = twig({data: '{{ [1,5,2,7,8]|map((v) => v*v) }}'});
testTemplate.render().should.equal('1,25,4,49,64');
});
});

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 b656062

Please sign in to comment.