Folder Setup
We need some folder so make some folders inside your src
folder.
- components
- context
- utils
Setup the utils
folder
utils
folder will contain all the utility functions that we will use in our project.
client/src/utils/index.js
//calculate the days left from the date calculating
export const daysLeft = (deadline) => {
const difference = new Date(deadline).getTime() - Date.now();
const remainingDays = difference / (1000 * 3600 * 24);
return remainingDays.toFixed(0);
};
//calculate the percentage of the goal that has been reached
//How much money has been raised so far
export const calculateBarPercentage = (goal, raisedAmount) => {
const percentage = Math.round((raisedAmount * 100) / goal);
return percentage;
};
//Check if the image is valid or not using the url
export const checkIfImage = (url, callback) => {
const img = new Image();
img.src = url;
if (img.complete) callback(true);
img.onload = () => callback(true);
img.onerror = () => callback(false);
};
daysLeft(deadline)
: This function takes adeadline
as an input, which should be a date string or a date object. It calculates the difference between the current date and the deadline in milliseconds, then converts it into days by dividing by the number of milliseconds in a day (1000 ms * 3600 s * 24 h). The result is rounded to zero decimal places usingtoFixed(0)
and returned.
calculateBarPercentage(goal, raisedAmount)
: This function takes two numbers as input:goal
(the target amount to be raised) andraisedAmount
(the amount raised so far). It calculates the percentage of the goal that has been reached by dividingraisedAmount
bygoal
and multiplying by 100. The result is then rounded to the nearest integer usingMath.round()
and returned.
checkIfImage(url, callback)
: This function takes a URL string and a callback function as input. It creates a new Image object (img
) and sets itssrc
attribute to the given URL. If the image has already been loaded (indicated byimg.complete
), the callback function is called withtrue
as its argument. If the image loads successfully, theonload
event handler calls the callback withtrue
. If there's an error loading the image, theonerror
event handler calls the callback withfalse
. This function is used to check if a given URL is a valid image or not.