diff --git a/Maths/ZellersCongruenceAlgorithm.js b/Maths/ZellersCongruenceAlgorithm.js new file mode 100644 index 000000000..728fc9cc1 --- /dev/null +++ b/Maths/ZellersCongruenceAlgorithm.js @@ -0,0 +1,26 @@ +// Zeller's Congruence Algorithm finds the day of the week from the Gregorian Date. Wikipedia: https://en.wikipedia.org/wiki/Zeller%27s_congruence +export const zellersCongruenceAlgorithm = (day, month, year) => { + if (typeof day !== 'number' || typeof month !== 'number' || typeof year !== 'number') { + throw new TypeError('Arguments are not all numbers.') + } + const q = day + let m = month + let y = year + if (month < 3) { + m += 12 + y -= 1 + } + day = + (q + Math.floor(26 * (m + 1) / 10) + (y % 100) + Math.floor((y % 100) / 4) + Math.floor(Math.floor(y / 100) / 4) + (5 * Math.floor(y / 100))) % + 7 + const days = [ + 'Saturday', + 'Sunday', + 'Monday', + 'Tuesday', + 'Wednesday', + 'Thursday', + 'Friday' + ] + return days[day] +} diff --git a/Maths/test/ZellersCongruenceAlgorithm.test.js b/Maths/test/ZellersCongruenceAlgorithm.test.js new file mode 100644 index 000000000..931a9348a --- /dev/null +++ b/Maths/test/ZellersCongruenceAlgorithm.test.js @@ -0,0 +1,17 @@ +import { zellersCongruenceAlgorithm } from '../ZellersCongruenceAlgorithm' + +function testZeller (day, month, year, expected) { + test('Testing on ' + day + '/' + month + '/' + year, () => { + expect(zellersCongruenceAlgorithm(day, month, year)).toBe(expected) + }) +} + +test('Testing on this/should/throw', () => { + expect(() => { + zellersCongruenceAlgorithm('this', 'should', 'error') + }).toThrowError(new TypeError('Arguments are not all numbers.')) +}) +testZeller(25, 1, 2013, 'Friday') +testZeller(26, 1, 2013, 'Saturday') +testZeller(16, 4, 2022, 'Saturday') +testZeller(25, 4, 2022, 'Monday')