There is a way to refactor this logic expression?
A && B && B > A
Just learning and I would like to know another way of writing the same expression Thank you
Split the expressions and put them in variables with readable names.
Due to the lack of information about what A and B are, I assume the first half of the expression makes sure both values are truthy and then you compare them:
const bothTruthy= A && B;
const BLargerThanA = B > A;
const yourExpression = bothTruthy && BLargerThanA;
Update:
Okay, the below solution doesn't work for all cases.
I think you don't need to refactor your expression logic if you want A and B to be interpreted as true. During the processing of logical expressions, the engine independently optimizes them and performs a lazy way, for example: if in the expression A && (B || C) the value A is interpreted as false, then the processing of the expression will end immediately and the value A will be returned (false or an equivalent value), but if the value of A is interpreted astrue, then processing of the condition will continue. Further, if B is interpreted as true, then due to logical addition(OR), processing will end with a value equivalent to true, and if B is interpreted as false, then processing will continue...
Try this - A && (B > A)
const cases = [
[true, false],
[false, true],
[false, false],
[true, true],
[1, 2],
[2, 1],
[1, 0],
[0, 1],
[undefined, 1],
[1, undefined],
[undefined, 0],
[0, undefined],
[null, undefined],
[undefined, null],
[1, NaN],
[NaN, 1],
[0, NaN],
[NaN, 0],
[{}, 0],
[1, {}],
[{}, []],
[[], {}],
['2', 1],
[1, '2'],
[true, 1],
[1, true],
[true, '1'],
['1', true],
[0, -1],
[-1, 0],
[1, -1],
[-1, 1],
[false, -1],
[-1, false]
];
const fails = [];
cases.forEach((c) => {
const [A, B] = c;
const r1 = A && B && (B > A);
const r2 = A && (B > A); // <-- simplified condition
const r = !!r1 === !!r2;
if (!r) fails.push({c: c, r1, r2});
});
if (fails.length > 0) {
console.log('Not all cases passed!');
console.log(fails);
} else {
console.log('All cases passed!');
}
.as-console-wrapper { min-height: 100%!important; top: 0; }