complete-javascript-course
complete-javascript-course copied to clipboard
171 Adding Dates to _Bankist_ App - I've got an elegant implementation
Well, I like the idea of Janas sharing flowcharts with a viewer since you understand logic and conditions and eventually are able to try to implement some code on your own. That's how it should always be. When I took Node.JS course it was quite impossible to go ahead. I used to re-write many lines of code so that I managed to follow the "picture".
By default the method would return a current date provided no arguments have been passed in.
const getCurrentDate = (date = new Date()) => {
const option = { day: '2-digit', month: '2-digit', year: 'numeric'};
return date.toLocaleString('uk-UA', option);
};
I call the method in a main function which is getLatestUpdateValues() each time we need to update the information
const getLatestUpdateValues = (account) => {
labelDate.textContent = getCurrentDate();
displayMovements(account);
labelBalance.textContent =
`${getCurrentBalance(account).toFixed(2)}€`;
labelSumIn.textContent =
`${getMonthlyDeposits(account).toFixed(2)}€`;
labelSumOut.textContent =
`${getMonthlyWithdrawals(account).toFixed(2)}€`;
};
However in displayMovements method in a forEach loop, I pass arguments to the getCurrentDate()
const movementsDate =
getCurrentDate(new Date(account.movementsDates[index])); // Jonas uses i instead of index variable.
By the end of the lesson everything seems to be working.
By the way.... Once again, I went ahead, implemented a method getDaysAgo() and realized that there had been an issue with sorting. It became more explicit one I started to differentiate days in the result. I created a switch which would return a current movement as a Today, an operation which made yesterday would be displayed as "yesterday", others days - as "days".
const getDaysAgo = (dateOfMovement) => {
const currentDate = new Date().getTime();
let daysAgo = (currentDate - dateOfMovement) / 1000 / 60 / 60 / 24;
daysAgo = Math.trunc(daysAgo);
switch (daysAgo) {
case 0: return `today`;
case 1: return `yesterday`;
default: return `${daysAgo} days ago`;
}
}
the problem is in const displayMovements = function(account, sort = false)
const money = sort
? account.movements.slice().sort((a, b) => a - b)
: account.movements;
We've sorted all elements creating a new array though the array with dates hasn't changed its order!