Skip to content

Instantly share code, notes, and snippets.

@cihanselim
Created March 24, 2021 11:28
Show Gist options
  • Save cihanselim/1ac60a9d20644e8473596a9134ff2878 to your computer and use it in GitHub Desktop.
Save cihanselim/1ac60a9d20644e8473596a9134ff2878 to your computer and use it in GitHub Desktop.
// Sample Wallet Data
const wallet = [
{ value: 30.3, rate: 400.12, type: 'GAU' },
{ value: 1520, rate: 7.82, type: 'USD' },
{ value: 20, rate: 403.2, type: 'GAU' },
{ value: 345, rate: 10.14, type: 'EUR' }
];
// Sample Currencies
const currentRates = {
GAU: 450.44,
USD: 7.98,
EUR: 9.45
};
const formatAmount = (number, fraction = 2) => Number(number.toFixed(fraction));
const getSummary = () => {
const summary = {};
const getTotalByKey = key =>
Object.keys(summary).reduce((i, j) => {
return i + summary[j][key];
}, 0);
const getSummaryItem = (value, spentMoney, currentMoney, profit) => {
return {
value,
spentMoney: formatAmount(spentMoney),
currentMoney: formatAmount(currentMoney),
profit: formatAmount(profit)
};
};
Object.keys(currentRates).forEach(typeRateKey => {
const walletItems = wallet.filter(item => item.type === typeRateKey);
const value = walletItems.reduce((i, j) => {
return i + j.value;
}, 0);
const spentMoney = walletItems.reduce((i, j) => {
return i + j.value * j.rate;
}, 0);
const currentMoney = currentRates[typeRateKey] * value;
const profit = currentMoney - spentMoney;
summary[typeRateKey] = getSummaryItem(value, spentMoney, currentMoney, profit);
});
summary.TOTAL = getSummaryItem(
null,
getTotalByKey('spentMoney'),
getTotalByKey('currentMoney'),
getTotalByKey('profit')
);
return summary;
};
console.table(getSummary());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment