JSFiddle - React, Tailwind, and code Playground

by cvoll

JavaScript

const seats = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16];

const minQuantity = 1;
const maxQuantity = 8;

const minListings = 1;
const maxListings = 3;

const between = (min, max) => Math.floor(Math.random() * (max - min + 1) + min);

const numListings = between(minListings, maxListings);

const totalSeats = seats.length;
let seatsRemaining = totalSeats;
let cursor = 0;
let listings = [];

for (let i = 0; i < numListings; i++) {
  const quantity = Math.min(between(minQuantity, maxQuantity), seatsRemaining);
  listings.push({ quantity });
  seatsRemaining -= quantity;
}

listings = listings.map((listing, i) => {
  // For each listing, there's only a particular window that we can put it in
  // i.e., we can put it anywhere, as long as there's enough room to the right
  // for the remaining listings
  const otherListingsQuantity = listings.slice(i + 1, listings.length).reduce((total, listing) => {
  	return total + listing.quantity;
  }, 0);

  const closestStart = cursor;
  const farthestStart = Math.max(cursor, totalSeats - listing.quantity - otherListingsQuantity);

  const start = between(closestStart, farthestStart);
  cursor = start + listing.quantity;

  listing.seats = [];

  for (let i = 0; i < listing.quantity; i++) {
    listing.seats.push(seats[i + start]);
  }
  return listing;
});