Home > database >  Replacing conditional chaining with an older method
Replacing conditional chaining with an older method

Time:09-13

I have some code that is using conditional chaining such as

productQuantity = purchases.filter((pObj) => pObj.elements[0]?.prodType?.id === purchase.elements[0]?.prodType?.id && pObj.sold === purchase.sold).length

It works fine but I need to convert the chained conditionals to an older method and I'm not sure how. Can anyone advise ?

Reason being that PM2 does not support chaining conditional operators.

CodePudding user response:

Let's try this. Replacing all key?.key2 with key && key.key2

productQuantity = purchases.filter((pObj) => {
    return pObj.elements[0] && pObj.elements[0].prodType && purchase.elements[0] && purchase.elements[0].prodType && pObj.elements[0].prodType.id === purchase.elements[0].prodType.id && pObj.sold === purchase.sold
}).length

CodePudding user response:

I would probably do something like this.

First, we make the observation that the we are selecting an id from two similar objects: we can therefore refactor the logic required to select the id into a common function:

function selectId(item) {
    if (item) {
        const elements = item.elements;
        if (elements) {
            const element = elements[0];
            if (element) {
                const prodType = element.prodType;
                if (prodType) {
                    const id = prodType.id;
                    return id;
                }
            }
        }
    }
}

You could also flatten the selection (which may or may not be more readable/maintainable):

function selectId(item) {
  if (!item) return undefined;

  const elements = item.elements;
  if (!elements) return undefined;

  const element = elements[0];
  if (!element) return undefined;

  const prodType = element.prodType;
  if (!element) return undefined;

  const id = prodType.id;
  return id;
}

Once you have that, then your filter comes down to this:

productQuantity = purchases.filter( isMatch ).length;

function isMatch(obj) {
    let itemId = selectId(obj);
    let purchaseId = selectId(purchase);
    const shouldKeep = itemId == purchaseId
                  && obj.sold === purchase.sold;
    return shouldKeep
}
  • Related