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

后端 未结 9 1588
[愿得一人]
[愿得一人] 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:15

    No, it's not. Given the same input, this function will return different values. And then you can't build a 'table' that maps the input and the outputs.

    From the Wikipedia article for Pure function:

    The function always evaluates the same result value given the same argument value(s). The function result value cannot depend on any hidden information or state that may change while program execution proceeds or between different executions of the program, nor can it depend on any external input from I/O devices

    Also, another thing is that a pure function can be replaced with a table which represents the mapping from the input and output, as explained in this thread.

    If you want to rewrite this function and change it to a pure function, you should pass the random value as an argument too

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

    and then call it this way (example, with 2 and 5 as min and max):

    test( Math.random(), 2, 5)
    

提交回复
热议问题