Skip to content

Instantly share code, notes, and snippets.

@mutoo
Last active March 15, 2023 23:04
Show Gist options
  • Save mutoo/a63df5db234c2b9173c6666e96c0c6ee to your computer and use it in GitHub Desktop.
Save mutoo/a63df5db234c2b9173c6666e96c0c6ee to your computer and use it in GitHub Desktop.
caldulated day of week with zellersCongruence, by GPT-4
// Zeller's Congruence function
function zellersCongruence(year, month, day) {
if (month < 3) {
month += 12;
year -= 1;
}
const A = year % 100;
const B = Math.floor(year / 100);
const F = A + Math.floor(A / 4) + Math.floor(B / 4) - 2 * B + Math.floor(13 * (month + 1) / 5) + day;
let result = ((F % 7) + 7) % 7;
// Adjust the result so that 0 represents Sunday, 1 represents Monday, and so on
if (result === 0) {
result = 7;
}
return result - 1;
}
// Function to get the day of the week using JavaScript Date object
function getDayOfWeek(year, month, day) {
const date = new Date(year, month - 1, day);
return date.getDay();
}
// Simple assert function
function assertEqual(actual, expected, message) {
if (actual === expected) {
console.log(`[PASSED] ${message}`);
} else {
console.error(`[FAILED] ${message}: expected ${expected}, but got ${actual}`);
}
}
// Test cases for Zeller's Congruence function
function testZellersCongruence() {
const testCases = [
{ year: 2023, month: 8, day: 13 },
{ year: 2021, month: 1, day: 1 },
{ year: 2000, month: 12, day: 31 },
{ year: 1987, month: 10, day: 11 },
{ year: 1776, month: 7, day: 4 },
];
testCases.forEach(({ year, month, day }) => {
const expectedResult = getDayOfWeek(year, month, day);
const actualResult = zellersCongruence(year, month, day);
const message = `${year}-${month}-${day} should be ${expectedResult}`;
assertEqual(actualResult, expectedResult, message);
});
}
// Run the tests
testZellersCongruence();
// [PASSED] 2023-8-13 should be 0
// [PASSED] 2021-1-1 should be 5
// [PASSED] 2000-12-31 should be 0
// [PASSED] 1987-10-11 should be 0
// [PASSED] 1776-7-4 should be 4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment