I'm not sure what exactly do you mean by the "best" way to solve your problem, because you have not specified the criteria to evaluate the solution against. Seeing the functional-programming among other tag makes me write some code which I think is relevant.
In the code below (which you can test out here):
- First
map()
translates each work period into a set of days in such period. This will result in "array of arrays".
reduce()
flattens the arrays into a single one.
- The
map()
is then formatting each moment.js Moment
object into its string representaion.
- Finally,
join(' ')
transforms it in into a single string where all the dates are space separated.
If you write in ES6 or TypeScript:
const sourceObject = {
"workPeriods": [
{"user_id":"9345bf", "startDate":"2018-02-05T05:00:00.000Z", "endDate":"2018-02-09T05:00:00.000Z"},
{"user_id":"80c3a9", "startDate":"2018-02-12T05:00:00.000Z", "endDate":"2018-02-16T05:00:00.000Z"},
{"user_id":"35jh87", "startDate":"2018-02-19T05:00:00.000Z", "endDate":"2018-02-23T05:00:00.000Z"}
]
};
const userFriendlyWorkPeriodsDayList = sourceObject
.workPeriods
.map(workPeriod => {
const allDaysInRange = [];
const currentDate = moment(workPeriod.startDate);
const endDate = moment(workPeriod.endDate);
while (currentDate.isBefore(endDate)) {
allDaysInRange.push(currentDate.clone());
currentDate.add(1, 'days');
}
return allDaysInRange;
})
.reduce((accumulator, current) => (accumulator.push(...current), accumulator), [])
.map(date => date.format('MM/DD'))
.join(' ');
const result = `Work days: ${userFriendlyWorkPeriodsDayList}`;
Same code rewritten in older versions of JavaScript require usage of function
keyword instead of =>
. They may also lack spread operator support (.push(...arrayOfValuesBeingPushed)
).
const sourceObject = {
"workPeriods": [
{"user_id":"9345bf", "startDate":"2018-02-05T05:00:00.000Z", "endDate":"2018-02-09T05:00:00.000Z"},
{"user_id":"80c3a9", "startDate":"2018-02-12T05:00:00.000Z", "endDate":"2018-02-16T05:00:00.000Z"},
{"user_id":"35jh87", "startDate":"2018-02-19T05:00:00.000Z", "endDate":"2018-02-23T05:00:00.000Z"}
]
};
const userFriendlyWorkPeriodsDayList = sourceObject
.workPeriods
.map(function (workPeriod) {
const allDaysInRange = [];
const currentDate = moment(workPeriod.startDate);
const endDate = moment(workPeriod.endDate);
while (currentDate.isBefore(endDate)) {
allDaysInRange.push(currentDate.clone());
currentDate.add(1, 'days');
}
return allDaysInRange;
})
.reduce(function (accumulator, current) { accumulator.push(...current); return accumulator; }, [])
.map(function (date) { return date.format('MM/DD'); })
.join(' ');
const result = `Work days: ${userFriendlyWorkPeriodsDayList}`;
console.log(result)