continue icon indicating copy to clipboard operation
continue copied to clipboard

Prefer using nullish coalescing operator (`??`) instead of a logical or

Open bjornjorgensen opened this issue 1 year ago • 1 comments

To address the problem and prefer using the nullish coalescing operator (??) instead of the logical OR (||), you should replace the logical OR with the nullish coalescing operator in your code. The nullish coalescing operator (??) will return the right-hand operand when the left-hand operand is either null or undefined, as opposed to the logical OR (||), which returns the right-hand operand for any falsy value of the left-hand operand (e.g., 0, '', false, null, undefined, NaN).

Here’s how you can fix the problem in your code:

return content.reduce((acc, part) => {
  return acc + (part.type === "imageUrl"
    ? countImageTokens(part)
    : encoding.encode(part.text ?? "", "all", []).length);
}, 0);

By applying this change, part.text ?? "" ensures that if part.text is either null or undefined, it falls back to an empty string, which seems to be the intended behavior. Unlike the logical OR, this method won't replace other falsy values (like an empty string, 0, or false) with "", making it a safer choice in this context.

bjornjorgensen avatar Mar 03 '24 13:03 bjornjorgensen

i'm using sonarlint image

bjornjorgensen avatar Mar 03 '24 13:03 bjornjorgensen

Thanks! Might try SonarLint myself to catch more like this

sestinj avatar Mar 09 '24 06:03 sestinj