Array.map() strange behaviour

Posted on
  • Consider this code snippet :

     var lvls = [65535,54038,47824,39322,32768,26526,18388,11818,5958],
        halfDiff = 2979;
    
    function anaGetKey(samples){
      var keys = samples.map(function(v) {
        var i;
        var val = v + halfDiff;
        for (i=0; i<lvls.length; i++){
          if (lvls[i] < val){
            console.log("found : "+i+" for "+v+" - "+val);
            break;
          }
        }
        console.log(" => return "+i);
        return i;
      });
      console.log(keys);
    }
    
    anaGetKey([6000,12000,54000,65000]);
    

    Why does map return 1 for the 65000 case ?

             |_| espruino.com
     2v09 (c) 2021 G.Williams
    >found : 8 for 6000 - 8979
     => return 8
    found : 7 for 12000 - 14979
     => return 7
    found : 1 for 54000 - 56979
     => return 1
    found : 0 for 65000 - 67979
     => return 1
    [ 8, 7, 1, 1 ]
    > 
    

    It prints 'found : 0', meaning i==0 and the last element of the keys array is 1 ?

    What am I missing ?

  • Messed up the code insert - see below

    var lvls = [65535,54038,47824,39322,32768,26526,18388,11818,5958],
        halfDiff = 2979; //2958/2
    
    function anaGetKey(samples){
      var keys = samples.map(function(v)  {
        var i;
        var val = v + halfDiff;
        for (i=0; i<lvls.length; i++)    {
          if (lvls[i] < val){
            console.log("found : "+i+" for "+v+" - "+val);
            break;
          }
        }
        console.log(" => return "+i);
        return i;
      });
      console.log(keys);
    }
    
    anaGetKey([6000,12000,54000,65000]);
    
    
  • Hi, this looks like an Espruino issue - maybe not related to map specifically, but it looks like if you break out of a FOR loop then it's possible the iterator still gets called before it exits?

    Changing break for return i will fix it:

    var lvls = [65535,54038,47824,39322,32768,26526,18388,11818,5958],
        halfDiff = 2979; //2958/2
    function anaGetKey(samples){
      var keys = samples.map(function(v)  {
        var i;
        var val = v + halfDiff;
        for (i=0; i<lvls.length; i++)    {
          if (lvls[i] < val){
            console.log("found : "+i+" for "+v+" - "+val);
            return i; //<------- here
          }
        }
        console.log(" => return "+i);
        return i;
      });
      console.log(keys);
    }
    anaGetKey([6000,12000,54000,65000]);
    

    I'm on holiday next week but i've just filed a bug for this at https://github.com/espruino/Espruino/issues/2012 and I'll get on it when I get back

  • Thank you for the quick reply.

  • Post a reply
    • Bold
    • Italics
    • Link
    • Image
    • List
    • Quote
    • code
    • Preview
About

Array.map() strange behaviour

Posted by Avatar for jgw @jgw

Actions