You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何重构函数避免代码重复?用单个参数替代重复入参

JavaScript函数重构:消除代码重复并改用单个location参数

原问题场景

现有两个存在大量代码重复的JavaScript函数,需要重构为接收单个location对象参数的形式,同时消除重复代码,要求通过formatLocationInfo调用formatAddressLocation实现逻辑复用。

原函数代码如下:

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;
};

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;
};

重构方案

基础重构版本

先将formatAddressLocation改为接收location对象参数,从对象中解构所需字段;再让formatLocationInfo复用前者的逻辑,仅额外处理name字段:

// 重构后的核心地址格式化函数,接收location对象
export const formatAddressLocation = (location) => {
  const { postcode, house, additions, street } = location;
  let address = "";
  if (street) address += street + " ";
  if (house) address += house + " ";
  if (additions) address += additions + " ";
  if (postcode) address += postcode + " ";
  return address.trim(); // 优化:移除末尾多余空格
};

// 复用核心函数,处理name字段后拼接地址
export const formatLocationInfo = (location) => {
  const { name } = location;
  let address = "";
  if (name) address += name + " ";
  address += formatAddressLocation(location);
  return address.trim();
};

简洁优化版本

可以用数组过滤+拼接的方式替代多个if判断,让代码更简洁:

export const formatAddressLocation = (location) => {
  const { postcode, house, additions, street } = location;
  // 过滤空值、undefined等假值后用空格拼接
  return [street, house, additions, postcode].filter(Boolean).join(" ");
};

export const formatLocationInfo = (location) => {
  const { name } = location;
  // 先处理name,再拼接核心函数返回的地址
  return [name, formatAddressLocation(location)].filter(Boolean).join(" ");
};

调用示例

// 调用formatAddressLocation
const basicAddress = formatAddressLocation({
  street: "长安街",
  house: "88号",
  postcode: "100001"
});
// 输出:"长安街 88号 100001"

// 调用formatLocationInfo
const fullLocation = formatLocationInfo({
  name: "天安门广场",
  street: "东长安街",
  postcode: "100006"
});
// 输出:"天安门广场 东长安街 100006"

内容的提问来源于stack exchange,提问作者codestarter

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 03:25:35