From 144ebceb37450521d68d92aeac1dcf6908e7648c Mon Sep 17 00:00:00 2001 From: Thijs Louisse Date: Wed, 15 May 2019 17:00:37 +0200 Subject: [PATCH] feat(localize): allow long/short/narrow param getMonthNames --- packages/localize/src/date/getMonthNames.js | 15 +++++++++++---- packages/localize/test/date/getMonthNames.test.js | 11 +++++++++++ 2 files changed, 22 insertions(+), 4 deletions(-) diff --git a/packages/localize/src/date/getMonthNames.js b/packages/localize/src/date/getMonthNames.js index 132b7c8fa..cb6388a0d 100644 --- a/packages/localize/src/date/getMonthNames.js +++ b/packages/localize/src/date/getMonthNames.js @@ -2,8 +2,14 @@ import { normalizeDate } from './normalizeDate.js'; const monthsLocaleCache = {}; -export function getMonthNames({ locale }) { - let months = monthsLocaleCache[locale]; +/** + * @desc Returns month names for locale + * @param {string} options.locale locale + * @param {string} [options.style=long] long, short or narrow + * @returns {Array} like: ['Januray', 'February', ...etc]. + */ +export function getMonthNames({ locale, style = 'long' } = {}) { + let months = monthsLocaleCache[locale] && monthsLocaleCache[locale][style]; if (months) { return months; @@ -11,7 +17,7 @@ export function getMonthNames({ locale }) { months = []; - const formatter = new Intl.DateTimeFormat(locale, { month: 'long' }); + const formatter = new Intl.DateTimeFormat(locale, { month: style }); for (let i = 0; i < 12; i += 1) { const date = new Date(2019, i, 1); const formattedDate = formatter.format(date); @@ -19,7 +25,8 @@ export function getMonthNames({ locale }) { months.push(normalizedDate); } - monthsLocaleCache[locale] = months; + monthsLocaleCache[locale] = monthsLocaleCache[locale] || {}; + monthsLocaleCache[locale][style] = months; return months; } diff --git a/packages/localize/test/date/getMonthNames.test.js b/packages/localize/test/date/getMonthNames.test.js index cb2925b78..538717013 100644 --- a/packages/localize/test/date/getMonthNames.test.js +++ b/packages/localize/test/date/getMonthNames.test.js @@ -18,4 +18,15 @@ describe('getMonthNames', () => { s`一月 二月 三月 四月 五月 六月 七月 八月 九月 十月 十一月 十二月`, ); }); + it('supports "short" style', () => { + expect(getMonthNames({ locale: 'en-GB', style: 'short' })).to.deep.equal( + s`Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec`, + ); + expect(getMonthNames({ locale: 'nl-NL', style: 'short' })).to.deep.equal( + s`jan. feb. mrt. apr. mei jun. jul. aug. sep. okt. nov. dec.`, + ); + expect(getMonthNames({ locale: 'zh-CH', style: 'short' })).to.deep.equal( + s`1月 2月 3月 4月 5月 6月 7月 8月 9月 10月 11月 12月`, + ); + }); });