diff --git a/server/utils/date.js b/server/utils/date.js index 3c74c1a..7034f3e 100644 --- a/server/utils/date.js +++ b/server/utils/date.js @@ -1,16 +1,13 @@ +import padding from './padding'; + function makeTodaysDate() { const now = new Date(Date.now()); const [year, month, day] = [ now.getFullYear(), - now.getMonth(), - now.getDay(), + now.getMonth() + 1, + now.getDate(), ]; - const padding = (num) => { - const padded = num > 10 ? `${num}` : `0${num}`; - return padded; - }; - return `${year}-${padding(month)}-${padding(day)}`; } diff --git a/server/utils/padding.js b/server/utils/padding.js new file mode 100644 index 0000000..6a264f5 --- /dev/null +++ b/server/utils/padding.js @@ -0,0 +1,9 @@ +const padding = (number) => { + if (Number.isNaN(Number(number)) || Number(number) < 1) return -1; + if (`${number}`.length > 1 || number > 10) { + return `${number}`; + } + return `0${number}`; +}; + +export default padding; diff --git a/tests/utils/date.spec.js b/tests/utils/date.spec.js index b017f45..244aa38 100644 --- a/tests/utils/date.spec.js +++ b/tests/utils/date.spec.js @@ -2,6 +2,7 @@ import chai from 'chai'; import 'chai/register-should'; import dirtyChai from 'dirty-chai'; import makeTodaysDate from '../../server/utils/date'; +import padding from '../../server/utils/padding'; chai.use(dirtyChai); @@ -17,8 +18,8 @@ describe('Today\'s Date Utility Function', () => { it('should return today\'s date', () => { const today = new Date(Date.now()); makeTodaysDate().should.be.a('string').that.has.a.lengthOf('YYYY-MM-DD'.length); - makeTodaysDate().should.be.a('string').which.includes(today.getDay()); - makeTodaysDate().should.be.a('string').which.includes(today.getMonth()); + makeTodaysDate().should.be.a('string').which.includes(padding(today.getDate())); + makeTodaysDate().should.be.a('string').which.includes(padding(today.getMonth() + 1)); makeTodaysDate().should.be.a('string').which.includes(today.getFullYear()); }); }); diff --git a/tests/utils/padding.spec.js b/tests/utils/padding.spec.js new file mode 100644 index 0000000..371ccb2 --- /dev/null +++ b/tests/utils/padding.spec.js @@ -0,0 +1,19 @@ +import 'chai/register-should'; +import padding from '../../server/utils/padding'; + +describe('Padding Function', () => { + it('should return a padded number as string given a single digit', () => { + padding(2).should.be.a('string').that.has.lengthOf(2); + }); + + it('should not pad numbers which are not single digits', () => { + padding(200).should.be.eql('200'); + padding('01').should.be.eql('01'); + }); + + it('should only pad numbers', () => { + padding('Hey!').should.be.eql(-1); + padding('22').should.be.eql('22'); + padding('1').should.be.eql('01'); + }); +});