diff --git a/src/utils/periodToString.ts b/src/utils/periodToString.ts new file mode 100644 index 0000000..7a7fd2c --- /dev/null +++ b/src/utils/periodToString.ts @@ -0,0 +1,13 @@ +import pluralise from './pluralise' + +const periodToString = (years: number, months: number): string => { + let text = '' + + if (years > 0) text += `${years} ${pluralise('year', years)}` + if (years > 0 && months > 0) text += ' and ' + if (months > 0) text += `${months} ${pluralise('month', months)}` + + return text +} + +export default periodToString \ No newline at end of file diff --git a/src/utils/utils.ts b/src/utils/utils.ts index 37568ce..f0d9d36 100644 --- a/src/utils/utils.ts +++ b/src/utils/utils.ts @@ -3,6 +3,7 @@ import cast from './cast' import dateHelpers from './dateHelpers' import formatDate from './formatDate' import numberToCurrency from './numberToCurrency' +import periodToString from './periodToString' import pluralise from './pluralise' export default { @@ -10,6 +11,7 @@ export default { cast: cast, formatDate: formatDate, dateHelpers: dateHelpers, + periodToString: periodToString, pluralise: pluralise, numberToCurrency: numberToCurrency } \ No newline at end of file diff --git a/test/utils/periodToString.test.ts b/test/utils/periodToString.test.ts new file mode 100644 index 0000000..27aee10 --- /dev/null +++ b/test/utils/periodToString.test.ts @@ -0,0 +1,28 @@ +import periodToString from '../../src/utils/periodToString' +import { expect } from 'chai' + +describe('periodToString', () => { + it('returns \'3 years\' when the years are 3 and the months are 0', () => { + const result = periodToString(3, 0) + + expect(result).to.equal('3 years') + }) + + it('returns \'3 months\' when the years are 0 and the months are 3', () => { + const result = periodToString(0, 3) + + expect(result).to.equal('3 months') + }) + + it('returns \'1 year and 1 month\' when the years are 1 and the months are 1', () => { + const result = periodToString(1, 1) + + expect(result).to.equal('1 year and 1 month') + }) + + it('returns \'3 years and 3 months\' when the years are 3 and the months are 3', () => { + const result = periodToString(3, 3) + + expect(result).to.equal('3 years and 3 months') + }) +})