Saurav Pathak
Saurav Pathak

Reputation: 836

Is there a way to apply rules to all arguments of a function at once?

Lets consider a javascript function doTruncate with 5 arguments. I want to trim all whitespaces from all arguments.

const doTruncate = function (pre = "", firstName = "", middleName = "", lastName = "", post = "") {
  pre = pre.strim()
  firstName = firstName.trim()
  middleName = middleName.trim()
  lastName = lastName.trim()
  post = post.trim()

  let result = pre + " " + firstName + " " + middleName + " " + lastName + " " + post;
  return result.trim();
};

Is there a better way to do this instead of individually trimming each argument?

Upvotes: 0

Views: 46

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 371049

I'd use rest parameters, then trim each of them in the array:

const doTruncate = (...args) => {
  return args.slice(0, 5) // this slice can be removed if the function
         // is always called with 5 or less arguments
    .map(str => (str || '').trim()) // the `|| ''` is only needed 
           // if `undefined` may be explicitly passed
           // in the middle of the argument list
           // while later arguments are non-empty
    .join(' ')
    .trim(); // this last trim can be removed
             // if the first and last parameters, when passed, aren't empty
};

Upvotes: 1

Related Questions