Skip to content

Commit

Permalink
feat: support literal string in format
Browse files Browse the repository at this point in the history
  • Loading branch information
ngryman committed Aug 13, 2020
1 parent 703d0ad commit 7a38cdb
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 5 deletions.
11 changes: 6 additions & 5 deletions src/formatDate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,20 +23,21 @@ const formatters: Formatters = {
}

const createCustomPattern = (customFormatters: CustomFormatters) =>
Object.keys(customFormatters).reduce((pattern, key) => `|${key}`, '')
Object.keys(customFormatters).reduce((_, key) => `|${key}`, '')

export default function formatDate(
customFormatters: CustomFormatters,
format: string,
parts: DateParts,
date: Date
): string {
const literalPattern = '\\[([^\\]]+)\\]|'
const customPattern = createCustomPattern(customFormatters)
const patternRegexp = new RegExp(`${defaultPattern}${customPattern}`, 'g')
const patternRegexp = new RegExp(`${literalPattern}${defaultPattern}${customPattern}`, 'g')

const allFormatters = { ...formatters, ...customFormatters }

return format.replace(patternRegexp, (mask: FormatterMask) =>
(allFormatters[mask] || identity)(parts, date)
)
return format.replace(patternRegexp, (mask: FormatterMask, literal: string) => {
return literal || (allFormatters[mask] || identity)(parts, date)
})
}
5 changes: 5 additions & 0 deletions test/formatDate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,3 +22,8 @@ test('format a 2 digits 24-hour', testMask, 'HH', '16')
test('format a 2 digits hour', testMask, 'hh', '04')
test('format a 2 digits minute', testMask, 'mm', '13')
test('format a 2 digits second', testMask, 'ss', '37')

test('format a date with a literal string', t => {
const dateStr = formatDate({}, '[It is] dddd[,] MMMM DD[th]', tokens, tokensDate)
t.is(dateStr, 'It is Tuesday, January 17th')
})

0 comments on commit 7a38cdb

Please sign in to comment.