Skip to content

Instantly share code, notes, and snippets.

@abel-masila
Last active March 24, 2023 21:24
Show Gist options
  • Save abel-masila/05f6a3efb0f424cfd5afd56b89befd19 to your computer and use it in GitHub Desktop.
Save abel-masila/05f6a3efb0f424cfd5afd56b89befd19 to your computer and use it in GitHub Desktop.
hard stuff
function combineCustomNights(customNights) {
const result = [];
let currentRange = null;
customNights.sort((a, b) => new Date(a.date) - new Date(b.date));
customNights.forEach((night) => {
if (!currentRange) {
currentRange = { start: night.date, end: night.date, rooms: { ...night } };
delete currentRange.rooms.date;
} else {
const nextDate = new Date(currentRange.end);
nextDate.setDate(nextDate.getDate() + 1);
if (night.date === currentRange.end || night.date === nextDate.toISOString().slice(0, 10)) {
currentRange.end = night.date;
Object.keys(night).forEach((key) => {
if (key !== 'date') {
currentRange.rooms[key] = (currentRange.rooms[key] || 0) + night[key];
}
});
} else {
result.push(currentRange);
currentRange = { start: night.date, end: night.date, rooms: { ...night } };
delete currentRange.rooms.date;
}
}
});
if (currentRange) {
result.push(currentRange);
}
return result;
}
const customNights = [
{ "date": "2023-03-14", "standardRooms": 1 },
{ "date": "2023-03-15", "suite": 1 },
{ "date": "2023-03-15", "standardRooms": 1, "doubleRooms": 2 },
{ "date": "2023-03-17", "standardRooms": 1 }
];
console.log(combineCustomNights(customNights));
@abel-masila
Copy link
Author

output is:
[
{
"start": "2023-03-14",
"end": "2023-03-15",
"rooms": {
"standardRooms": 2,
"suite": 1,
"doubleRooms": 2
}
},
{
"start": "2023-03-17",
"end": "2023-03-17",
"rooms": {
"standardRooms": 1
}
}
]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment