简体   繁体   中英

How to pass single param instead of duplication?

How correctly refactor function, instead of duplication

so, now I have:

export const formatAddressLocation = (postcode, house, additions, street) => {
  let address = "";
  if (street) address += street + " ";
  if (house) address += house + " ";
  if (additions) address += additions + " ";
  if (postcode) address += postcode + " ";
  return address;
};

and
export const formatLocationInfo = (name, postcode, house, additions, street) => {
  let address = "";
  if (name) address += name + " ";
  if (street) address += street + " ";
  if (house) address += house + " ";
  if (additions) address += additions + " ";
  if (postcode) address += postcode + " ";
  return address;
};

Something like (location) = {loction.name} + formatAddressLocation(…)

Just move the name param to the end of the params, and use the second function.

export const formatAddressLocation = (postcode, house, additions, street, name) => {
  let address = "";
  if (name) address += name + " ";
  if (street) address += street + " ";
  if (house) address += house + " ";
  if (additions) address += additions + " ";
  if (postcode) address += postcode + " ";
  return address;
};

You can pass params in object

your function would look like this

export const formatLocationInfo = ({name, postcode, house, additions, street}) => {
  let address = "";
  if (name) address += name + " ";
  if (street) address += street + " ";
  if (house) address += house + " ";
  if (additions) address += additions + " ";
  if (postcode) address += postcode + " ";
  return address;
};

you can call your funtion like

let obj = {
   name: "",
   postcode: "",
   house: "",
   additions: "",
   street: "",
}

let address = formatLocationInfo(obj)

or

let address = formatLocationInfo({name: "", postcode: "", house: "",additions: "", street: ""})

You can use the following code:

result = `${locationName ? locationName + ' ' : ''} ${formatAddressLocation(postcode, house, additions, street)}`;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM