Earlier today I had to spend a whole *20 minutes* coming up with this function. It’s like a modulo function, but instead of looping back to zero every cycle, it transitions back down to zero. It cycles every **2(n-1)** elements. There’s probably a proper name for it, but I can’t figure it out.

In case anyone else would rather google it than spend time figuring it out, here it is:

defping_pong_mod(i, n): cycle = 2 * (n - 1) i = i % cycle if i >= n: return cycle - i return i

I hope this is helpful to a fellow lazy person in the future.

Hello, I am a lazy person and you saved me a lot of trouble, so thank you!

In my case I wanted the “book-ends” to be repeated, like this:

p4(x) = 0, 1, 2, 3, 3, 2, 1, 0, 0, 1, 2…

so I had to modify it slightly:

function ping_pong_mod(i, n){

let cycle = 2 * n

i = i % cycle

if (i >= n)

return cycle – 1 – i

return i

}