import toDate from '../toDate/index' ; import formatters from '../_lib/format/lightFormatters/index' ; import getTimezoneOffsetInMilliseconds from '../_lib/getTimezoneOffsetInMilliseconds/index' ; import isValid from '../isValid/index' ; import subMilliseconds from '../subMilliseconds/index' ; import requiredArgs from '../_lib/requiredArgs/index' ; const formattingTokensRegExp = /(\w)\1*|''|'(''|[^'])+('|$)|./g ; const escapedStringRegExp = /^'([^]*?)'?$/ ; const doubleQuoteRegExp = /''/g ; const unescapedLatinCharacterRegExp = /[a-zA-Z]/ ; name category summary description param { Date | Number } date param { String } format returns { String } throws throws example type Token = keyof typeof formatters ; export default function lightFormat ( dirtyDate , formatStr ) { requiredArgs ( 2 , arguments ) ; const originalDate = toDate ( dirtyDate ) ; if ( ! isValid ( originalDate ) ) { throw new RangeError ( 'Invalid time value' ) ; } const timezoneOffset = getTimezoneOffsetInMilliseconds ( originalDate ) ; const utcDate = subMilliseconds ( originalDate , timezoneOffset ) ; const tokens = formatStr . match ( formattingTokensRegExp ) ; if ( ! tokens ) return '' ; const result = tokens . map ( ( substring ) => { if ( substring === "''" ) { return "'" ; } const firstCharacter = substring [ 0 ] ; if ( firstCharacter === "'" ) { return cleanEscapedString ( substring ) ; } const formatter = formatters [ firstCharacter as Token ] ; if ( formatter ) { return formatter ( utcDate , substring ) ; } if ( firstCharacter . match ( unescapedLatinCharacterRegExp ) ) { throw new RangeError ( 'Format string contains an unescaped latin alphabet character `' + firstCharacter + '`' ) ; } return substring ; } ) . join ( '' ) ; return result ; } function cleanEscapedString ( input ) { const matches = input . match ( escapedStringRegExp ) ; if ( ! matches ) { return input ; } return matches [ 1 ] . replace ( doubleQuoteRegExp , "'" ) ; }