I have a function that receives two arguments that I want them to be optional (the last two):
const renderDate = (date, locale, format) => {
if (locale === undefined) { locale = 'en' }
if (format === undefined) { format = 'D MMM' }
if (locale === 'de' && format === 'D MMM') {
const indexD = format.lastIndexOf('D')
format = `${format.slice(0, indexD + 1)}o${format.slice(indexD + 1, format.length)}`
}
moment.locale(locale)
return moment(date).format(format)
}
console.log(renderDate('2019-09-04', 'Do MMM'));
<script src="https://momentjs.com/downloads/moment.js"></script>
I can't do something like this:
const renderDate = (date, locale = 'en', format = 'D MMM') => {
if (locale === 'de' && format === 'D MMM') {
const indexD = format.lastIndexOf('D')
format = `${format.slice(0, indexD + 1)}o${format.slice(indexD + 1, format.length)}`
}
moment.locale(locale)
return moment(date).format(format)
}
Because if I call the method with just 1 optional argument, it can be wrong:
renderDate('2019-09-04', 'Do MMM')
Now locale (the language) is a format, which is wrong.
What is the best approach to solve this issue? Should I pass an object and then check if the keys are present?
Then I could destructure, but I am not sure if this is the best approach:
const renderDate = ({
date,
locale,
format
}) => {
if (locale === undefined) {
locale = 'en'
}
if (format === undefined) {
format = 'D MMM'
}
if (locale === 'de' && format === 'D MMM') {
const indexD = format.lastIndexOf('D')
format = `${format.slice(0, indexD + 1)}o${format.slice(indexD + 1, format.length)}`
}
moment.locale(locale)
return moment(date).format(format)
}
console.log(renderDate('2019-09-04', 'Do MMM'));
<script src="https://momentjs.com/downloads/moment.js"></script>