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

Kiwi Rupela picture Kiwi Rupela · Oct 31, 2017 · Viewed 15k times · Source

Is the following a pure function?

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

My understanding is that a pure function follows these conditions:

  1. It returns a value computed from the parameters
  2. It doesn't do any work other than calculating the return value

If this definition is correct, is my function a pure function? Or is my understanding of what defines a pure function incorrect?

Answer

Christian Benseler picture Christian Benseler · Oct 31, 2017

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)