Skip to content

Commit

Permalink
#8: better solution to get number of weeks in a year.
Browse files Browse the repository at this point in the history
  • Loading branch information
babruix committed Oct 14, 2016
1 parent bc798ba commit 5a5bf61
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 44 deletions.
32 changes: 6 additions & 26 deletions src/officialValidators/week.js
Original file line number Diff line number Diff line change
Expand Up @@ -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}
22 changes: 4 additions & 18 deletions src/officialValidators/week.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
})
})
});
});

0 comments on commit 5a5bf61

Please sign in to comment.