Home

Published

- 1 min read

CodeWars - Unlucky Days

img of CodeWars - Unlucky Days

Problem

The question is basically count the number of instances of Friday the 13th in a given year.

Original Problem: https://www.codewars.com/kata/56eb0be52caf798c630013c0

Tools needed

In order to solve this Problem you first need to be aware of the Standard Date-Object. MDN JavaScript Date

You will need to know two things

  1. How to initialize a Date const date = new Date(year, month, day)
  2. How to query the Date to get a given day. this is done with the Date.prototype.getDay() method.

Solution

To solve the problem we simply have to ask for each month of the year if it has a friday 13th. So we need a counter, and a loop for the months of the year, and then just return the value of the counter.

Code Solution

const unluckyDays = (year: number): number => {
	const FRIDAY = 5
	const UNLUCKY_DAY = 13

	let count = 0
	for (let month = 1; month < 13; month++) {
		const date = new Date(year, month, UNLUCKY_DAY)
		if (date.getDay() === FRIDAY) {
			count++
		}
	}
	return count
}

Note: it might seem that using constants for the two values FRIDAY and UNLUCKY_DAY are unnecessary. However it is good practice to avoid as many magic numbers as possible.