name-taken
New Coder
Hello everyone!
I was messing around with using conditionals to assign values to variables and see up to which point could I simplify the code to a single line.
I'm just checking for the maximum and the minimum values from a set by using a
One solution would be to do this:
Now, obviously if statements could do this clearer, but I wanted to see if I could do this in with a one-liner approach. This was my initial attempt:
This works for the most part, except when dealing with negative numbers. I swapped the connector AND with an OR:
However, this didn't quite work. Now, this is extremely weird to me as this is the only language I've seen where you can use conditionals like this to assign to a variable. From a Boolean algebra standpoint, I do not how this is really being evaluated. Upon which conditions?
Anyway, I tried every possible way to see if I could get it working, and I did. But by negating the assignments:
Can someone provide some input to how this works? How is this being evaluated? How come negating the assignments work? I just can't wrap my head around this...
I was messing around with using conditionals to assign values to variables and see up to which point could I simplify the code to a single line.
I'm just checking for the maximum and the minimum values from a set by using a
forEach
.One solution would be to do this:
JavaScript:
let max = Number.MIN_VALUE,
min = Number.MAX_VALUE;
set.forEach((num) => {
num > max && (max = num);
num < min && (min = num);
}
Now, obviously if statements could do this clearer, but I wanted to see if I could do this in with a one-liner approach. This was my initial attempt:
JavaScript:
let max = Number.MIN_VALUE,
min = Number.MAX_VALUE;
set.forEach((num) => num > max && (max = num) && num < min && (num = min));
This works for the most part, except when dealing with negative numbers. I swapped the connector AND with an OR:
JavaScript:
let max = Number.MIN_VALUE,
min = Number.MAX_VALUE;
set.forEach((num) => (num > max && (max = num)) || (num < min && (min = max)));
However, this didn't quite work. Now, this is extremely weird to me as this is the only language I've seen where you can use conditionals like this to assign to a variable. From a Boolean algebra standpoint, I do not how this is really being evaluated. Upon which conditions?
Anyway, I tried every possible way to see if I could get it working, and I did. But by negating the assignments:
JavaScript:
set.forEach((num) => (num > max && !(max = num)) || (num < min && !(min = num)));
Can someone provide some input to how this works? How is this being evaluated? How come negating the assignments work? I just can't wrap my head around this...
Last edited: