1

Here is my code :

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

All I want is finding better way to optimize my code and reduce if condition in my code. Is there any suggestion ?

1

4 Answers 4

2

You can avoid the typing of if when you wrap it into a function and the typing of data with destructuring.
The advantage of wrapping the if in this case into a function is that you can simply test it, it is reusable and easy to read

Code

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

Working Example

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)

Sign up to request clarification or add additional context in comments.

1 Comment

Nice, simple way of doing it.
0

A simpler way:

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

1 Comment

ReferenceError: Invalid left-hand side in assignment
0

Let's imagine you have many fields or you want to modify them, you would create a map. Right now, your code works and my solution is overkill but it may be useful in the future:

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))

It is not simpler but it is more extensible, and when you have many parameters, it is going to be much faster on a big scale. It is also reusable. Hope that helps!

Comments

0

Not sure if you'd consider this as code optimization, but you can get rid of the if statements using 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 },
      },
    )
};

If you can use newer JS features (with a transpiler or otherwise), you could use Object rest/spread for a slightly more concise syntax:

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

Edit 1: note that all these are pure functions, no mutations are taking place whatsoever

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.