Reputation: 169
In a ternary or if statement, I often want the value to equal the value of what is being tested for example
//b is a integer or '-'
//a should be an integer
const a = b === '-' ? -1 : b
The statement I am using for a is
const a = expr.match(/.*?\((.*)[a-z].*/)[1]
so it would be nice to know if there is a single line way to have it work so i'm not repeating a complicated expression that may change.
Upvotes: 0
Views: 178
Reputation: 1
If you want to get value only one time use below mentioned script.
var a = (b = expr.match(/.*?\((.*)[a-z].*/)[1]) == '-' ? -1 : b;
Upvotes: 0
Reputation: 781059
Just assign the variable first.
let b = b = expr.match(/.*?\((.*)[a-z].*/)[1];
const a = b == '-' ? -1 : b;
If you really want a one-liner, you can assign b
within the expression.
const a = (b = expr.match(/.*?\((.*)[a-z].*/)[1]) == '-' ? -1 : b;
But you should have declared b
earlier. You can reuse the same temporary variable every time, so you only have to declare it once and use it in all the one-liners.
If you need this pattern in multiple places, define a function.
function if_dash(expr) {
return expr == '-' ? -1 : expr;
}
const a = if_dash(expr.match(/.*?\((.*)[a-z].*/)[1]);
Upvotes: 1