continue
continue copied to clipboard
Prefer using nullish coalescing operator (`??`) instead of a logical or
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.
i'm using sonarlint
Thanks! Might try SonarLint myself to catch more like this