-
-
Save uonick/a2eb650fc8a3a7f60d2eccbecf51f1fc to your computer and use it in GitHub Desktop.
Calendar Matrix (date-fns, ES6) inspired by https://github.com/bclinkinbeard/calendar-matrix
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import getYear from 'date-fns/get_year' | |
import getMonth from 'date-fns/get_month' | |
import addDays from 'date-fns/add_days' | |
import startOfWeek from 'date-fns/start_of_week' | |
const rows = range(6) | |
const cols = range(7) | |
/** | |
* Returns a two-dimensional array with calendar represented dates | |
*/ | |
export default function ({ year, month, weekStartsOn } = { | |
year: getYear(new Date()), | |
month: getMonth(new Date()), | |
weekStartsOn: 0 | |
}) { | |
const matrix = [] | |
const date = new Date(year, month) | |
let curDate = startOfWeek(date, { weekStartsOn }) | |
rows.forEach(row => { | |
const week = [] | |
cols.forEach(col => { | |
week.push(curDate) | |
curDate = addDays(curDate, 1) | |
}) | |
matrix.push(week) | |
}) | |
return matrix | |
} | |
/** | |
* Returns an array range from 0 to n | |
*/ | |
function range (n) { | |
return [...Array(n).keys()] | |
} |
Author
uonick
commented
Jun 18, 2022
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment