NodeJs - 优化多个if

时间:2017-09-18 06:52:52

标签: javascript node.js mongoose

这是我的代码:

Search.prototype.makeQuery = function (data) {
    let result = {};
    if (data.orderId) {
        result["order_id"] = data.orderId;
    }
    if (data.userMobileNumber) {
        result["user.Number"] = {$regex : data.userMobileNumber}
    }
    if (data.userFullName) {
        result["user.Name"] = {$regex: data.userFullName}
    }
    return result;
};

我想要的只是找到更好的方法来优化我的代码并减少代码中的if条件。有什么建议吗?

4 个答案:

答案 0 :(得分:2)

当您将if包装到一个函数中并使用destructuring键入data时,您可以避免输入{/ 1}}。 在这种情况下将if包装到函数中的优点是您可以简单地测试它,它是可重用的并且易于阅读

代码

Search.prototype.makeQuery = function (data) {
    let result = {}
    let {orderId, userMobileNumber, userFullName} = data
    setObjectValue(orderId, result, "order_id", orderId)
    setObjectValue(userMobileNumber, result, "user.Number", {$regex : userMobileNumber})
    setObjectValue(userFullName, result, "user.Name", {$regex: userFullName})
    return result;
}

function setObjectValue(condition, object, key, value) {
    if(condition) {
        object[key] = value
    }
}

工作示例

function makeQuery (data) {
    let result = {}
    let {orderId, userMobileNumber, userFullName} = data
    setObjectValue(orderId, result, "order_id", orderId)
    setObjectValue(userMobileNumber, result, "user.Number", {$regex : userMobileNumber})
    setObjectValue(userFullName, result, "user.Name", {$regex: userFullName})
    return result;
}

function setObjectValue(condition, object, key, value) {
    if(condition) {
        object[key] = value
    }
}

let data = {
    orderId: 1,
    userMobileNumber: "016875447895",
    userFullName: "John Doe"
}

let query = makeQuery(data)

console.log(query)

答案 1 :(得分:0)

更简单的方法:

Search.prototype.makeQuery = function (data) {
    let result = {};    
    data.orderId && (result["order_id"] = data.orderId);
    data.userMobileNumber && (result["user.Number"] = {$regex : data.userMobileNumber});
    data.userFullName && (result["user.Name"] = {$regex: data.userFullName});
    return result;
};

答案 2 :(得分:0)

假设你有很多字段,或者想要修改它们,你可以创建一个地图。现在,你的代码有效,我的解决方案有点矫枉过正,但未来可能会有用:

const interestingData = new Map()
    //I tried to imitate your values. 
    // Use whatever function you want here as a callback. 
    // value is the value you request, the callback must return the value you want to set.
interestingData.set("order_id", value => value)
interestingData.set("user.Number", value => ({ $regevalue: value }))
interestingData.set("user.Name", value => ({ $regevalue: value }))

//Tgis is a Factory in case you need several search.
const makeSearch = fields => data => {
    let result = {}
    fields.forEach((callBack, field) => {
        if (data[field])
            result[field] = callBack(data[field])
    })
    return result
}

//Creating a searching function
const myResearch = makeSearch(interestingData)

//Fake examples
const data1 = {
    order_id: 'ertyui',
    "user.Number": "ertyuio",
    "user.Name": "ertyuio",
    azerr: 123456
}

const data2 = {
    order_id: 'ertyui',
    "user.Number": "ertyuio",

}

console.log(myResearch(data1))
console.log(myResearch(data2))

它不是更简单但它更强可扩展,当你有很多参数时,它会更强更快规模大。它也是可重复使用的。希望有所帮助!

答案 3 :(得分:0)

不确定您是否将此视为代码优化,但您可以使用if删除Object.assign语句:

Search.prototype.makeQuery = function (data) {
  return Object.assign({},
      data.orderId && { order_id: data.orderId },
      data.userMobileNumber && {
        'user.Number': { $regex : data.userMobileNumber },
      },
      data.userFullName && {
        'user.Name': { $regex : data.userFullName },
      },
    )
};

如果您可以使用较新的JS功能(使用转换器或其他方式),则可以使用Object rest/spread来获得更简洁的语法:

Search.prototype.makeQuery = (data) => ({
  ...data.orderId && { order_id: data.orderId },
  ...data.userMobileNumber && {
    'user.Number': { $regex : data.userMobileNumber },
  },
  ...data.userFullName && {
     user.Name': { $regex : data.userFullName },
  },
});

编辑1:请注意,所有这些都是纯函数,没有任何突变发生