We have UI editor from which user can select any number of days.
If the user selects continuous days, those are represented by dashes or hyphens, but if non-continuous days are selected then those are represented by commas..
eg - String - M,W,F
– Non Continuous days.
eg - String - M-F
– User selected continuous 5 days.
From backend point of view, if we are getting some string like M-Tu,Th,Sa-Su
or M-W,F-Su
etc combination, how to find the valid days from this ?.
I have created a constant array to either loop or check the value
DAYS: ['M', 'Tu', 'W', 'Th', 'F', 'Sa', 'Su']
let userInput = 'M-Tu,Th,Sa-Su' or 'M-W,F-Su'
SomeMethod(userInput) {
let validDays = [];
const commaSeperatedDays = userInput?.split(',');
const contDaysFromCommaSeparatedDays = commaSeperatedDays.map(x =>
x.split('-'));
let indDays = validDays.push(contDaysFromCommaSeparatedDays.map(x =>
findIndividualDays(x)));
//When only continuous days are there
const ContinuousDays = days?.split('-');
}
function findIndividualDays(days) {
//getting confused here how to handle cases - if there is any inbuilt library ?
if (days.length === 1) {
return days[0];
}
let indDays = [];
const startIndex = constants.DAYS.indexOf(days[0]);
const endIndex = constants.DAYS.indexOf(days[1]);
for (let index = startIndex; index <= endIndex; index++) {
const element = constants.DAYS[index];
indDays.push(element);
}
return { ...indDays };
}
3
Answers
Modified my solution little bit and this is working for me.
Just to add an option for fun, I like using generator functions