Convert this function from childhood times to something better?
<p>I needed to show some simple code example for friend, for example moving a button along the edge of the screen clockwise. Sure this is something very simple, no, this is simplest. But I found myself spending about almost 30 minutes on that. I was embarased, because I am professional programmer for 20+ years, and I even needed to start the program many times before the button was flying the right ways. And I was thinking, why? So I speculated that this kind of code is difficult to get right immediately, because it is very old style, each case is typed separately, each check must be entered manually, you need to go through each iteration and make carefully sure that all numbers and checks are exactly precisely correct, and this is hard to do because of the nature of code style, which is, eehh, spaghetti, messy?</p>

<p>So I was like, is there a way to convert it to "modern" way, like use loop instead of cases, use templates or other meta-programming, use functional approach or at least use arrays. And it seems I cannot find any good way for this.</p>

<pre><code>var mx = screen.width - b.w, my = screen.height - b.h

setInterval(function() {
    var step = 3
    if (state == 1) {
        b.x += step
        if (b.x &gt;= mx) b.x = mx, state++
    } else if (state == 2) {
        b.y += step
        if (b.y &gt;= my) b.y = my, state++
    } else if (state == 3) {
        b.x -= step
        if (b.x &lt;= 0) b.x = 0, state++
    } else if (state == 4) {
        b.y -= step
        if (b.y &lt;= 0) b.y = 0, state = 1
    }
    b.apply()
}, 1)
</code></pre>

<p>This is JavaScript, in C it would be even more difficult to get right fast, because you need to think about types.</p>

<p>Here is what I come up myself... This maybe demonstrating what I am trying to achieve. I am not talking about choosing different algorithm. but rather abotu exploring language(s) features, and programming techniques.</p>

<pre><code>var D = 3, name = ['x','y'], delta = [D,D,-D,-D], 
    limit = [screen.width - b.w, screen.height - b.h,0,0]

setInterval(function() {
    b[name[0]] += delta[0]
    if (delta[0] &gt; 0 &amp;&amp; b[name[0]] &gt; limit[0] || b[name[0]] &lt;= 0)
        b[name[0]] = limit[0],
        [name,delta,limit].some(function(x){ x.push(x.shift()) })
    b.apply()
},1)
</code></pre>

<p>This one at least separates data from code, making it simpler to get it right. It worked for me from the first attempt. But I am still not satisfied completely)</p>
