Reputation: 383
I am trying to slice the array based on the mathematical expressions in React. However, prettier extension does not let me do it as it removes parenthesis making the expression incorrect.
Here is example:
const paginateItems = items.slice(
pageIndex * itemsPerPage,
(pageIndex * itemsPerPage) * 2
)
And prettier changes that to
const paginateItems = items.slice(
pageIndex * itemsPerPage,
pageIndex * itemsPerPage * 2
)
How can I fix this so that it does not force my expression to be incorrect?
Upvotes: 2
Views: 3129
Reputation: 1074295
How can I fix this so that it does not force my expression to be incorrect?
It doesn't make your expression incorrect. *
is left-associative, meaning that a * b * c
is exactly the same as (a * b) * c
. The parens in that code don't make any difference to the result.
If your expression were pageIndex * (itemsPerPage * 2)
, the parens could make a difference to the result (in programming¹) if itemsPerPage
were really big (by causing overflow during itemsPerPage * 2
instead of causing overflow during pageIndex * itemsPerPage
, assuming pageIndex
is 2 or higher). So I would expect Prettier to leave them alone in that case. But with (pageIndex * itemsPerPage) * 2
, the ()
don't have any effect at all.
¹ "in programming" — In the world of mathematics, the parens in pageIndex * (itemsPerPage * 2)
wouldn't make any difference either, because multiplication is transitive (I think that's the word): a * b * c
is the same as (a * b) * c
is the same as a * (b * c)
. But in programming we deal with number types that have limited ranges and/or limited precisions at large magnitudes, so the order in which the two multiplication operations happen matters.
Upvotes: 5