From 5a5bf61f91b522541db8495b970ffb905ccaf054 Mon Sep 17 00:00:00 2001 From: babruix Date: Fri, 14 Oct 2016 23:34:17 +0300 Subject: [PATCH] #8: better solution to get number of weeks in a year. --- src/officialValidators/week.js | 32 ++++++----------------------- src/officialValidators/week.test.js | 22 ++++---------------- 2 files changed, 10 insertions(+), 44 deletions(-) diff --git a/src/officialValidators/week.js b/src/officialValidators/week.js index 36d620d..7fd6b67 100644 --- a/src/officialValidators/week.js +++ b/src/officialValidators/week.js @@ -20,32 +20,12 @@ function weekValidator(control) { } function weeksInYear(year) { - let lastDayOfTheYear = new Date(year, 11, 31); - const [, week] = getWeekNumber(lastDayOfTheYear); - if (week !== 1) { - return week; - } - - const dayOfTheMonth = lastDayOfTheYear.setDate(24); - return getWeekNumber(dayOfTheMonth)[1]; -} - -function getWeekNumber(d) { - // Copy date so don't modify original - let date = new Date(+d); - date.setHours(0, 0, 0); - - // Set to nearest Thursday: current date + 4 - current day number - // Make Sunday's day number 7 - date.setDate(date.getDate() + 4 - (date.getDay()||7)); - - // Get first day of year - const yearStart = new Date(date.getFullYear(),0,1); - // Calculate full weeks to nearest Thursday - const weekNo = Math.ceil(( ( (date - yearStart) / 86400000) + 1) / 7); + const d = new Date(year, 0, 1); + const isLeap = new Date(year, 1, 29).getMonth() === 1; - // Return array of year and week number - return [date.getFullYear(), weekNo]; + // Check for a Jan 1 that's a Thursday or a leap year that has a + // Wednesday jan 1. Otherwise year has 52 weeks. + return d.getDay() === 4 || isLeap && d.getDay() === 3 ? 53 : 52 } -export {weekValidator as default, weeksInYear, getWeekNumber} +export {weekValidator as default, weeksInYear} diff --git a/src/officialValidators/week.test.js b/src/officialValidators/week.test.js index 77e91b9..1acd315 100644 --- a/src/officialValidators/week.test.js +++ b/src/officialValidators/week.test.js @@ -5,27 +5,13 @@ import { weeksInYear, getWeekNumber } from './week'; describe('weeksInYear', () => { it(`should return 52 for year 2014 `, () => { expect(weeksInYear(2014)).toBe(52); - }) + }); it(`should return 53 for year 2015 `, () => { expect(weeksInYear(2015)).toBe(53); - }) + }); it(`should return 52 for year 2016 `, () => { expect(weeksInYear(2016)).toBe(52); - }) -}) - -describe('getWeekNumber', () => { - it(`should return 1 for new Date(2014, 11, 31)`, () => { - expect(getWeekNumber(new Date(2014, 11, 31))[1]).toBe(1); - }) - - it(`should return 53 for new Date(2015, 11, 31)`, () => { - expect(getWeekNumber(new Date(2015, 11, 31))[1]).toBe(53); - }) - - it(`should return 52 for new Date(2016, 11, 31)`, () => { - expect(getWeekNumber(new Date(2016, 11, 31))[1]).toBe(52); - }) -}) + }); +});