Month Calendar Grid Builder for UIs

Build a flat seven-column calendar grid for any month, honoring a configurable first weekday and blank padding cells.

JavascriptData Integrity

Code

javascriptsnippet
22 lines
export function buildMonthGrid(year, month, options = {}) {
  if (!Number.isInteger(year) || year < 1 || year > 9999) {
    throw new RangeError("year must be an integer between 1 and 9999");
  }
  if (!Number.isInteger(month) || month < 1 || month > 12) {
    throw new RangeError("month must be an integer between 1 and 12");
  }
  const weekStartsOn = options.weekStartsOn ?? 0;
  if (!Number.isInteger(weekStartsOn) || weekStartsOn < 0 || weekStartsOn > 6) {
    throw new RangeError("weekStartsOn must be an integer between 0 and 6");
  }
  const first = new Date(Date.UTC(year, month - 1, 1));
  const daysInMonth = new Date(Date.UTC(year, month, 0)).getUTCDate();
  const offset = (first.getUTCDay() - weekStartsOn + 7) % 7;
  const totalCells = Math.ceil((offset + daysInMonth) / 7) * 7;
  const cells = [];
  for (let index = 0; index < totalCells; index += 1) {
    const day = index - offset + 1;
    cells.push(day >= 1 && day <= daysInMonth ? day : null);
  }
  return { year, month, weekStartsOn, cells };
}

How the snippet works

Count the functions offset and buildMonthGrid as the entire surface area of Month Calendar Grid Builder for UIs.

The one repetition in this snippet is the loop for (let index = 0; index < totalCells; index += 1). When the guard condition holds, RangeError is thrown rather than a bogus value returned.

The result comes back as an object carrying year, month, weekStartsOn.

Applying it

The primary signature is export function buildMonthGrid(year, month, options = {})

The surface worth importing is buildMonthGrid; the helpers around it are private to the snippet.

The call returns year, month, weekStartsOn — destructure what you need at the call site.

Statements that matter

throw new RangeError("weekStartsOn must be an integer between 0 and 6");
throw new RangeError("year must be an integer between 1 and 9999");
throw new RangeError("month must be an integer between 1 and 12");

Interactive Tools for This Topic

FAQ

Does `buildMonthGrid` modify its input?
No. The code builds and returns a new value and leaves the arguments untouched, so it is safe to call on shared or frozen data structures.
What happens if the preconditions do not hold?
`RangeError` is raised at the guard, so invalid state never reaches the main logic.
Is a package install part of the setup?
No. Installation is unnecessary because only built-in APIs are used. The file defines `offset`, `buildMonthGrid` at load time.