Skip to content

Schedule Day-of-Week Bitmask

Matches recurring trip schedules to the current day of the week using bitwise operations. Used by the dispatcher service to determine which scheduled trips to create each day.


Where It Is Used

apps/api-server/src/schedules/dispatcher.service.ts

The dispatcher runs on a cron job and creates pending Trip records for each schedule that applies to today.


Data Model

Each Schedule record has a daysOfWeek integer field that encodes which days the schedule is active as a bitmask:

Day Index Bit Value
Sunday 0 bit 0 1
Monday 1 bit 1 2
Tuesday 2 bit 2 4
Wednesday 3 bit 3 8
Thursday 4 bit 4 16
Friday 5 bit 5 32
Saturday 6 bit 6 64

Example: A Mon–Fri schedule: daysOfWeek = 2 + 4 + 8 + 16 + 32 = 62 = 0b0111110


Algorithm

const today = new Date().getDay();         // 0 (Sun) – 6 (Sat)
const todayBit = 1 << today;               // e.g., Tuesday → 1 << 2 = 4 = 0b100

const activeSchedules = schedules.filter(
  s => (s.daysOfWeek & todayBit) !== 0    // bitwise AND: is today's bit set?
);

For each active schedule, the dispatcher creates a Trip record with status: PENDING and the scheduled start time.


Efficiency

A single bitwise AND replaces a day-name string comparison or array membership check. At typical schedule counts (<500), the difference is negligible, but the bitmask also makes the admin UI straightforward — each day checkbox sets or clears one bit:

// Toggle a day in the UI
function toggleDay(daysOfWeek: number, dayIndex: number): number {
  return daysOfWeek ^ (1 << dayIndex);
}

// Check if a day is active
function isDayActive(daysOfWeek: number, dayIndex: number): boolean {
  return (daysOfWeek & (1 << dayIndex)) !== 0;
}