Math.wrap

Posted on
  • I have problems with Math.wrap.
    When I run it in a program, it does not wrap, but if I enter it in the console it wraps it ok.

    // test.js
    
    var tmp = [];
    var i = 0;
    var k = 0;
    
    function onInit() {
    
    
      for(var j = 0; j < 30; j++) {
        tmp[i] = i;
        console.log('k = ' + k +'  ' + 'i = ' + i);
        Math.wrap(k++, 10);
        i++; if(i > 9) {i = 0;}
    
    
      }
    
      console.log(tmp);
      console.log(tmp.length);
    
    
    }
    setTimeout(onInit, 100);
    
    /*
    k = 0  i = 0
    k = 1  i = 1
    k = 2  i = 2
    k = 3  i = 3
    k = 4  i = 4
    k = 5  i = 5
    k = 6  i = 6
    k = 7  i = 7
    k = 8  i = 8
    k = 9  i = 9
    k = 10  i = 0
    k = 11  i = 1
    k = 12  i = 2
    k = 13  i = 3
    k = 14  i = 4
    k = 15  i = 5
    k = 16  i = 6
    k = 17  i = 7
    k = 18  i = 8
    k = 19  i = 9
    k = 20  i = 0
    k = 21  i = 1
    k = 22  i = 2
    k = 23  i = 3
    k = 24  i = 4
    k = 25  i = 5
    k = 26  i = 6
    k = 27  i = 7
    k = 28  i = 8
    k = 29  i = 9
    [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
    10
    >k
    =30
    >Math.wrap(k++, 10)
    =0
    >Math.wrap(k++, 10)
    =1
    >Math.wrap(k++, 10)
    =2
    >Math.wrap(k++, 10)
    =3
    >Math.wrap(k++, 10)
    =4
    >Math.wrap(k++, 10)
    =5
    >Math.wrap(k++, 10)
    =6
    >Math.wrap(k++, 10)
    =7
    >Math.wrap(k++, 10)
    =8
    >Math.wrap(k++, 10)
    =9
    >Math.wrap(k++, 10)
    =0
    >Math.wrap(k++, 10)
    =1
    >Math.wrap(k++, 10)
    =2
    >
    */
    

    On a Pico

  • Have you tried using modulo % instead of Math.wrap()?

  • Math.wrap doesn't alter the arguments, it just returns a wrapped value.

    As such Math.wrap(k++, 10); won't do anything - you'd probably want k=Math.wrap(k+1, 10);

    But as @MaBe says, for this kind of thing with just integers you could also easily use modulo: k=(k+1)%10;

  • I just wondered that it was different in a program and in the console.
    Because in line 80 it is 9, and in line 82 it is 0.

  • Maybe I'm misunderstanding... Math.wrap will return a number between 0 and 9, even though at line 80 in the code above, k itself will be somewhere around 40.

    In your uploaded code:

      for(var j = 0; j < 30; j++) {
        tmp[i] = i;
        console.log('k = ' + k +'  ' + 'i = ' + i);
        Math.wrap(k++, 10);
        i++; if(i > 9) {i = 0;}
      }
    

    The return value of Math.wrap isn't being used, so you might as well be doing:

      for(var j = 0; j < 30; j++) {
        tmp[i] = i;
        console.log('k = ' + k +'  ' + 'i = ' + i);
        k++;
        i++; if(i > 9) {i = 0;}
      }
    
  • Post a reply
    • Bold
    • Italics
    • Link
    • Image
    • List
    • Quote
    • code
    • Preview
About

Math.wrap

Posted by Avatar for Frida @Frida

Actions