Skip to content

Instantly share code, notes, and snippets.

@HichamBenjelloun
Last active January 5, 2022 02:27
Show Gist options
  • Save HichamBenjelloun/b56c3293d63802d5e50b546012b79c72 to your computer and use it in GitHub Desktop.
Save HichamBenjelloun/b56c3293d63802d5e50b546012b79c72 to your computer and use it in GitHub Desktop.
Find days of the year with a certain sum of digits
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);
@HichamBenjelloun
Copy link
Author

HichamBenjelloun commented Jan 4, 2022

To list all dates within the current year with the same sum of digits as the current day:

const addLeadingZero = (n: number) => `${n}`.padStart(2, '0');
const formatDate = (date: Date) => new Intl.DateTimeFormat('fr-FR', { dateStyle: 'short' }).format(date);

const currentDay = new Date();
const foundDays = findDays(sumOfDigits(currentDay), currentDay.getUTCFullYear());
console.log(`${foundDays.length} date(s) found.`);
console.log(foundDays.map(formatDate).join('\n'));

Output:

23 date(s) found.
04/01/2022
13/01/2022
22/01/2022
31/01/2022
03/02/2022
12/02/2022
21/02/2022
02/03/2022
11/03/2022
20/03/2022
02/04/2022
11/04/2022
05/10/2022
14/10/2022
23/10/2022
31/10/2022
03/11/2022
12/11/2022
21/11/2022
30/11/2022
02/12/2022
11/12/2022
20/12/2022

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment