From 7704fc1223a1c2a59d8cc6b35dc830d9e5826971 Mon Sep 17 00:00:00 2001 From: Alex Tselegidis Date: Tue, 11 Jan 2022 10:51:29 +0100 Subject: [PATCH] Move general functions methods to the date util. --- assets/js/utils/date.js | 125 +++++++++++++++++++++++++++++++++++++++- 1 file changed, 124 insertions(+), 1 deletion(-) diff --git a/assets/js/utils/date.js b/assets/js/utils/date.js index 4a252bbe..a276d371 100644 --- a/assets/js/utils/date.js +++ b/assets/js/utils/date.js @@ -64,7 +64,130 @@ window.App.Utils.Date = (function () { return dateMoment.format(format); } + /** + * Get the Id of a Weekday using the US week format and day names (Sunday=0) as used in the JS code of the + * application, case insensitive, short and long names supported. + * + * @param {String} weekDayName The weekday name among Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, + * Saturday. + + * @return {Number} Returns the ID of the weekday. + */ + function getWeekDayId(weekDayName) { + let result; + + switch (weekDayName.toLowerCase()) { + case 'sunday': + case 'sun': + result = 0; + break; + + case 'monday': + case 'mon': + result = 1; + break; + + case 'tuesday': + case 'tue': + result = 2; + break; + + case 'wednesday': + case 'wed': + result = 3; + break; + + case 'thursday': + case 'thu': + result = 4; + break; + + case 'friday': + case 'fri': + result = 5; + break; + + case 'saturday': + case 'sat': + result = 6; + break; + + default: + throw new Error(`Invalid weekday name provided: ${weekDayName}`); + } + + return result; + } + + /** + * Sort a dictionary where keys are weekdays + * + * @param {Object} weekDictionary A dictionary with weekdays as keys. + * @param {Number} startDayId Id of the first day to start sorting (From 0 for sunday to 6 for saturday). + + * @return {Object} Returns a sorted dictionary + */ + function sortWeekDictionary(weekDictionary, startDayId) { + const sortedWeekDictionary = {}; + + for (let i = startDayId; i < startDayId + 7; i++) { + const weekdayName = getWeekdayName(i % 7); + sortedWeekDictionary[weekdayName] = weekDictionary[weekdayName]; + } + + return sortedWeekDictionary; + } + + /** + * Get the name in lowercase of a Weekday using its Id. + * + * @param {Number} weekDayId The Id (From 0 for sunday to 6 for saturday). + + * @return {String} Returns the name of the weekday. + */ + function getWeekdayName(weekDayId) { + let result; + + switch (weekDayId) { + case 0: + result = 'sunday'; + break; + + case 1: + result = 'monday'; + break; + + case 2: + result = 'tuesday'; + break; + + case 3: + result = 'wednesday'; + break; + + case 4: + result = 'thursday'; + break; + + case 5: + result = 'friday'; + break; + + case 6: + result = 'saturday'; + break; + + default: + throw new Error(`Invalid weekday Id provided: ${weekDayId}`); + } + + return result; + } + return { - format + format, + getWeekDayId, + sortWeekDictionary, + getWeekdayName }; })();