JSFiddle - React, Tailwind, and code Playground
by cvoll
JavaScript
const input=[{section:"101",row:"A",seat:1},{section:"101",row:"A",seat:5},{section:"101",row:"A",seat:7},{section:"102",row:"B",seat:10},{section:"101",row:"A",seat:8},{section:"101",row:"A",seat:3},{section:"101",row:"B",seat:2},{section:"102",row:"B",seat:8},{section:"102",row:"B",seat:11},{section:"103",row:"H",seat:1},{section:"101",row:"A",seat:2}];
const expectedOutput = [
'Section 101, Row A, Seats 1, 2, 3, 5, 7, 8',
'Section 101, Row B, Seat 2',
'Section 102, Row B, Seats 8, 10, 11',
'Section 103, Row H, Seat 1'
];
let sectionMap = {};
let output = [];
input.forEach(seatmap => {
const { section, row, seat } = seatmap;
sectionMap[section] = sectionMap[section] || {};
sectionMap[section][row] = sectionMap[section][row] || [];
sectionMap[section][row].push(seat);
});
Object.keys(sectionMap).forEach(section => {
Object.keys(sectionMap[section]).forEach(row => {
const seats = sectionMap[section][row].sort();
const seatsLabel = seats.length === 1 ? 'Seat' : 'Seats';
output.push(`Section ${section}, Row ${row}, ${seatsLabel} ${prettyContiguousSeats(seats)}`);
});
});
console.log(output);
// (1, 1) -> false
// (1, 2) -> true
// (2, 1) -> true
// (3, 1) -> false
function seatsAreContiguous(a, b) {
return Math.abs(a - b) === 1;
}
// [1, 2, 3, 5, 7, 8] -> [[1, 2, 3], [5], [7, 8]
function groupContiguousSeats(seats = []) {
let groups = [];
seats = seats.sort((a, b) => a - b);
for (let i = 0; i < seats.length; i++) {
const currentSeat = seats[i];
const lastSeat = seats[i - 1];
if (i === 0 || !seatsAreContiguous(lastSeat, currentSeat)) {
groups.push([currentSeat]);
continue;
}
groups[groups.length - 1].push(currentSeat);
}
return groups;
}
// [1] -> '1'
// [1, 2] -> '1-2'
// [1, 2, 3] -> '1-3'
function prettySeatGroup(seatGroup = []) {
if (seatGroup.length === 1) {
return seatGroup[0];
}
return `${seatGroup[0]}-${seatGroup[seatGroup.length - 1]}`;
}
// [1, 2, 3, 5,...