Is a function that calls Math.random() pure?

后端 未结 9 1607
[愿得一人]
[愿得一人] 2021-01-30 15:30

Is the following a pure function?

function test(min,max) {
   return  Math.random() * (max - min) + min;
}

My understanding is that a pure func

9条回答
  •  春和景丽
    2021-01-30 16:13

    Would you be fine with the following:

    return ("" + test(0,1)) + test(0,1);
    

    be equivalent to

    var temp = test(0, 1);
    return ("" + temp) + temp;
    

    ?

    You see, the definition of pure is a function whose output does not change with anything other than its inputs. If we say that JavaScript had a way to tag a function pure and take advantage of this, the optimizer would be allowed to rewrite the first expression as the second.

    I have practical experience with this. SQL server allowed getdate() and newid() in "pure" functions and the optimizer would dedupe calls at will. Sometimes this would do something dumb.

提交回复
热议问题