Skip to content

Instantly share code, notes, and snippets.

@Sam-Kruglov
Created April 30, 2019 19:13
Show Gist options
  • Save Sam-Kruglov/5e79ec4884c45c9dc9f4b6f8e5670c79 to your computer and use it in GitHub Desktop.
Save Sam-Kruglov/5e79ec4884c45c9dc9f4b6f8e5670c79 to your computer and use it in GitHub Desktop.
Defining the sample code
import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.temporal.ChronoUnit;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
class BookingServiceTest {
static class Table {
int seats;
}
static class Booking {
/**
* Effective for 1 hour
*/
LocalDateTime time;
Table table;
}
static class BookingException extends RuntimeException {}
static class NoFreeTablesBookingException extends BookingException {}
/**
* The restaurant will close within less than 1 hour after the booking time.
*/
static class NoTimeUntilClosingBookingException extends BookingException {}
static class ClosedBookingException extends BookingException {}
/**
* Contains all tables and all bookings for each table.
* the list cannot be null
*/
static Map<Table, List<Booking>> tableToBookings = new HashMap<>();
/**
* The restaurant works every day from 9am to 8pm
*/
static LocalTime openingTime = LocalTime.of(9, 0);
static LocalTime closingTime = LocalTime.of(20, 0);
static Booking bookTable(int numberOfPeople, LocalDateTime time) {
final LocalTime bookingTime = time.toLocalTime();
if (bookingTime.isAfter(openingTime) && bookingTime.isBefore(closingTime)) {
if (bookingTime.isBefore(closingTime.minusHours(1))) {
return tableToBookings.entrySet()
.stream()
.filter(entry -> entry.getKey().seats >= numberOfPeople)
.sorted(Comparator.comparing(e -> e.getKey().seats))
.filter(entry -> entry.getValue()
.stream()
.map(booking -> booking.time)
.allMatch(bookedTime -> Duration.between(bookedTime, time)
.abs()
.get(ChronoUnit.HOURS) > 1)
)
.findFirst()
.map(entry -> {
Booking booking = new Booking();
booking.time = time;
booking.table = entry.getKey();
entry.getValue().add(booking);
return booking;
})
.orElseThrow(NoFreeTablesBookingException::new);
} else {
throw new NoTimeUntilClosingBookingException();
}
} else {
throw new ClosedBookingException();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment