Refactor JS method with multiple optional arguments

问题: 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 =...

问题:

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>


回答1:

Yes - an object is the only way to solve this if you can pass one, the other, or both of the two optional arguments. You can also use default values with this. And note that your if statement only runs if format is D MMM, so you can remove the indexOf and just use 0:

export const renderDate = ({ date, locale = "en", format = "D MMM" } = {}) => {
  if (locale === "de" && format === "D MMM") {
    const indexD = 0;
    format = `${format.slice(0, indexD + 1)}o${format.slice(indexD + 1, format.length)}`;
  }
  moment.locale(locale);
  return moment(date).format(format);
};
  • 发表于 2019-07-05 13:07
  • 阅读 ( 161 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除