feat(localize): allow long/short/narrow param getMonthNames
This commit is contained in:
parent
6cfa301d1c
commit
144ebceb37
2 changed files with 22 additions and 4 deletions
|
|
@ -2,8 +2,14 @@ import { normalizeDate } from './normalizeDate.js';
|
||||||
|
|
||||||
const monthsLocaleCache = {};
|
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) {
|
if (months) {
|
||||||
return months;
|
return months;
|
||||||
|
|
@ -11,7 +17,7 @@ export function getMonthNames({ locale }) {
|
||||||
|
|
||||||
months = [];
|
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) {
|
for (let i = 0; i < 12; i += 1) {
|
||||||
const date = new Date(2019, i, 1);
|
const date = new Date(2019, i, 1);
|
||||||
const formattedDate = formatter.format(date);
|
const formattedDate = formatter.format(date);
|
||||||
|
|
@ -19,7 +25,8 @@ export function getMonthNames({ locale }) {
|
||||||
months.push(normalizedDate);
|
months.push(normalizedDate);
|
||||||
}
|
}
|
||||||
|
|
||||||
monthsLocaleCache[locale] = months;
|
monthsLocaleCache[locale] = monthsLocaleCache[locale] || {};
|
||||||
|
monthsLocaleCache[locale][style] = months;
|
||||||
|
|
||||||
return months;
|
return months;
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -18,4 +18,15 @@ describe('getMonthNames', () => {
|
||||||
s`一月 二月 三月 四月 五月 六月 七月 八月 九月 十月 十一月 十二月`,
|
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月`,
|
||||||
|
);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue