const sortStrategies = {
descending: (prop) => (a, b) => b[prop] - a[prop],
ascending: (prop) => (a, b) => a[prop] - b[prop]
};
const sortCommands = {
thisYearIncome: {
descending: () => sortStrategies.descending('thisYearIncome'),
ascending: () => sortStrategies.ascending('thisYearIncome')
},
lastYearIncome: {
descending: () => sortStrategies.descending('lastYearIncome'),
ascending: () => sortStrategies.ascending('lastYearIncome')
},
rate: {
descending: () => sortStrategies.descending('rate'),
ascending: () => sortStrategies.ascending('rate')
}
};
function createSortCommand(order, prop) {
return sortCommands[prop][order]();
}
const data = [
{ thisYearIncome: 5000, lastYearIncome: 4000, rate: 0.25 },
{ thisYearIncome: 8000, lastYearIncome: 6000, rate: 0.33 },
{ thisYearIncome: 3000, lastYearIncome: 2000, rate: 0.5 },
{ thisYearIncome: 6000, lastYearIncome: 5000, rate: 0.2 }
];
function onSortChange(order, prop) {
const sortCommand = createSortCommand(order, prop);
fetchData(sortCommand);
}
function fetchData(sortCommand) {
const sortedData = data.sort(sortCommand);
console.log('Sorted Data:');
sortedData.forEach((item) => {
console.log(`This Year Income: ${item.thisYearIncome}, Last Year Income: ${item.lastYearIncome}, Rate: ${item.rate}`);
});
}
console.log('Sorting by This Year Income (Descending):');
onSortChange('descending', 'thisYearIncome');
console.log('\nSorting by Last Year Income (Ascending):');
onSortChange('ascending', 'lastYearIncome');
console.log('\nSorting by Rate (Descending):');
onSortChange('descending', 'rate');