Comment transformer une fonction fléchée en fonction de Javascript à papa. Utile, par exemple, lorsqu’on travaille avec Magento 2.
Note: la fonction d’exemple provient de ce sujet sur stack overflow: best way to filter based on dynamic condition.
Fonction fléchée (arrow function)
|
const data = [{ name: "Sam", age: 25, location: 'deleware', new_employee: true, shift: 'day' }, { name: "John", age: 45, location: 'new york', new_employee: false, shift: 'day' }, { name: "Tony", age: 65, location: 'california', new_employee: true, shift: 'evening' }, { name: "Bruce", age: 23, location: 'california', new_employee: true, shift: 'evening' }, { name: "Tom", age: 34, location: 'texas', new_employee: false, shift: 'day' }, { name: "Rob", age: 51, location: 'ohio', new_employee: false, shift: 'day' }, { name: "Jacob", age: 21, location: 'ohio', new_employee: false, shift: 'evening' }, { name: "Steve", age: 38, location: 'deleware', new_employee: false, shift: 'day' }], filters = [ ({ age }) => age < 30, ({ shift }) => shift === 'evening' ], result = data.filter(o => filters.every(fn => fn(o))); console.log(result); |
Fonction classique
|
function classicJS(myData, myFilters) { return myData.filter(function(o) { return myFilters.every(function(fn) { return fn(o); }); }); } console.log(classicJS(data, filters)); |
Autre exemple:
Fonction fléchée
|
getSumOfAllValuesFromSpecificKeyInObject: function(currentVisibleStoresArray, optionValue) { return currentVisibleStoresArray.reduce((total, obj) => helper.accessNestedObjectByStringPath(obj, optionValue) + total, 0); } |
Fonction classique
|
getSumOfAllValuesFromSpecificKeyInObject: function(currentVisibleStoresArray, optionValue) { return currentVisibleStoresArray.reduce(function(total, obj) { return helper.accessNestedObjectByStringPath(obj, optionValue) + total; }, 0); } |