"Calculator"-quickfix

Is there a quickfix which can convert

foo(1 + 2, 3 + 4 * 5);

to

foo(3, 23);

Thanks in advance.

Tom

0
7 comments
Avatar
Permanently deleted user

I don't think any exists, but if you compute the value like this, I believe it's better to keep the computation in place (for clarity purposes).

What I would do is create constants
public static int MY_CONSTANT = 1+2;

and use those in your code, this way you have both the explanation of the value, and the optimization (not computing it every time)

0
Avatar
Permanently deleted user

Hello Tom,

AFAIK, there's a "Compute constant value" intention available on each operator sign.

Sascha

0
Avatar
Permanently deleted user

Thanks. I was searching the inspection profile for "constant" or "math" but
could not find one. But clicking Alt+Enter on the operator shows the
quickfix - weird.

Tom

0
Avatar
Permanently deleted user

I've inlined a constant ...

0
Avatar
Permanently deleted user

It is not a quick fix but an intention. You can find it in the intention
setings.

Bas

Tom wrote:

Thanks. I was searching the inspection profile for "constant" or "math" but
could not find one. But clicking Alt+Enter on the operator shows the
quickfix - weird.

Tom

0
Avatar
Permanently deleted user

Thanks (again). Did not know intentions and inspections were separate things.

Tom

0

Yes! You can do this quickly with JavaScript or a small script in Python that evaluates simple arithmetic expressions inside function calls. Basically, you parse the arguments, evaluate them, and rebuild the call.

Here’s a JavaScript quickfix:

 

function quickEvalArgs(str) {  return str.replace(/\(([^()]+)\)/g, (match, args) => {    // split by commas, trim, evaluate each    const evaluated = args      .split(',')      .map(arg => eval(arg.trim()))      .join(', ');    return `(${evaluated})`;  }); } const input = "foo(1 + 2, 3 + 4 * 5);"; const output = quickEvalArgs(input); console.log(output); // foo(3, 23);

0

Please sign in to leave a comment.