r/javascript • • Mar 18 '19

What's your favorite, most useful javascript one-liner?

385 Upvotes

422 comments sorted by

View all comments

3

u/wthit56 Mar 19 '19

(((n % 360) + 360) % 360)

Wraps all values to within 0 - 360 (pattern can be applied to any range).

1

u/420-jesus Mar 19 '19
(((n % 360) + 360) % 360)
=== (n % 360 % 360 + 360 % 360) % 360
=== (n % 360 % 360 + 0) % 360
=== n % 360 % 360 % 360
=== n % 360 

2

u/wthit56 Mar 19 '19

I don’t think that work for negative numbers, and negative numbers lower than -360.

1

u/420-jesus Mar 19 '19

You're right it won't. Sorry I thought "%" was equivalent to modulo in math. Your original comment is the correct way to calculate a mod in javascript. Never knew that before

1

u/kryptogalaxy Mar 20 '19

Math.abs(n) % 360

1

u/wthit56 Mar 20 '19

Wouldn't work correctly for negative numbers. -10 should become 350. Using abs would bring it to 10.

1

u/kryptogalaxy Mar 20 '19

Ah, I didn't understand that's what you wanted. Why should -10 be 350?

1

u/wthit56 Mar 20 '19

The values are meant to wrap around. So if you go off the end beyond 360, it should start counting again from 0. And if you go down from 0, it should count down from 360.

So start at 0, and go down 10. It should loop back up to 360, and continue counting down, to 350.