Reputation: 2673
I have to convert a number to comma format. E.g 12345 => 12,345.
I have my solution :
function convert(n) { n = n.toString(); var result = ''; var count = 0, var idx = n.length - 1; while (r = n[idx]) { count++; result = ((count % 3 == 0 && count != n.length) ? ',' : '') + r + result; idx--; } return result; }
But someone else used :
result = ((count % 3 != 0 || count == n.length) ? '' : ',') + r + result;
They both work but now I am confused about my own solution and just lost why they both work. Ah not sure if my question is clear.
Upvotes: 1
Views: 120
Reputation: 6081
Assume that, count % 3 = 0
and count > n.length
Now your logic:
((count % 3 == 0 && count != n.length) ? ',' : '')
which means True && True
which results in True
hence the first
condition after ?
which is "," is selected.
Someone else logic:
((count % 3 != 0 || count == n.length) ? '' : ',')
which means 'False || False' which results in 'False' hence second
condition after ?
which is "," is selected.
P.S: Both are using similar logic
Upvotes: 0
Reputation: 1137
!(x AND y) is equal to !x OR !y
(and you can pull a NOT out of a boolean x by double negation, for example:
x == !!x
so
x AND !y (your original expression) is equivalent to !(!x OR y)
if you remove the negation (!) from the beginning, then you actually get the Negated form and that is why the second and third values of the ternary operator are reversed in your second example.
Upvotes: 2
Reputation: 25555
The two expressions are equivalent, the second one is just the negated version of yours. The opposite (more or less) of == is !=, the opposite of && is ||, and the opposite of true is false.
You are placing a comma whenever the count is divisible by 3 and you aren't at the start of the number. They are not placing a comma anytime the count is not divisible by 3 or they are at the start of the number.
Upvotes: 0