naomik - 1 month ago 4x

Javascript Question

I have

`let f = x => x % 4 === 0 ? 0 : 4 - x % 4`

But that's a piece of garbage function. Help.

`x`

Here's a sort of Table of Truth, or something.

`x x % 4 4 - (x % 4) f(x)`

0 0 4 0

1 1 3 3

2 2 2 2

3 3 1 1

4 0 4 0

5 1 3 3

6 2 2 2

7 3 1 1

8 0 4 0

9 1 3 3

I'm trying to find some correlations here, but it's late and I don't think my brain is working correctly.

What I'm seeing in the

`f(x)`

I'm sensing some use of

`Math.max`

`Math.min`

`Math.abs`

`x * -1`

`f`

Answer

Something like this will definitely do:

```
(4 - (x % 4)) % 4
```

Here's some more truth:

```
x x % 4 4 - (x % 4) (4 - (x % 4)) % 4
0 0 4 0
1 1 3 3
2 2 2 2
3 3 1 1
4 0 4 0
5 1 3 3
6 2 2 2
7 3 1 1
8 0 4 0
9 1 3 3
```

Source (Stackoverflow)

Comments