jashkenas/coffee-script — Issue #1971: Mod/intdiv Mathematical Operators to Work Around JavaScript Oddities
Author: mitsuhiko
Created: 2011-12-25 03:03:52+00:00
State: open

One of the weird aspects of JavaScript is how it defines modulo:

```
> (-3) % 4
-3
```

In comparison Python/Ruby define them to always have the sign of the right side:

```
>>> -3 % 4
1
```

Likewise it's very common to have to divide and require an integer result. As such I would propose two new operators '%%' for right handside signed mod and '//' for integer division:

```
a %% b
```

would compile to

```
(a % b + b) % b
```

And

```
a // b
```

would compile to

```
parseInt(a / b)
```

When is this useful? For instance consider wanting to move a player on a grid with the intent of mirroring over on edges:

```
goRight: ->
@x = (@x + 1) %% @boardWidth

goLeft: ->
@x = (@x - 1) %% @boardWidth
```

Another use case (where also the integer division comes in handy) is converting for instance things like global coordinates to locals:

```
getTile: (x, y) ->
sectionX = x // SECTION_WIDTH
sectionY = y // SECTION_HEIGHT
localX = x %% SECTION_WIDTH
localY = y %% SECTION_HEIGHT
section = @sections[sectionX][sectionY]
section[localX + localY * SECTION_WIDTH]
```