Last active
January 5, 2022 02:27
-
-
Save HichamBenjelloun/b56c3293d63802d5e50b546012b79c72 to your computer and use it in GitHub Desktop.
Find days of the year with a certain sum of digits
This file contains hidden or 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
const nthDay = (n, year) => { | |
const firstDay = new Date(`${year}`); | |
const newDay = new Date(firstDay.getTime()); | |
newDay.setDate(firstDay.getDate() + n); | |
return newDay; | |
}; | |
const isLeapYear = (year) => | |
((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0); | |
const getAllDays = (year) => { | |
const numberOfDays = isLeapYear(year) ? 366 : 365; | |
return new Array(numberOfDays) | |
.fill(0) | |
.map((_, index) => index) | |
.map(n => nthDay(n, year)); | |
}; | |
const sumOfDigits = (date) => | |
`${date.getUTCFullYear()}${date.getUTCMonth() + 1}${date.getUTCDate()}` | |
.split('') | |
.map(digit => Number(digit)) | |
.reduce((acc, cur) => acc + cur, 0); | |
const findDays = (sum, year) => getAllDays(year).filter(day => sumOfDigits(day) === sum); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
To list all dates within the current year with the same sum of digits as the current day:
Output: