Thursday, May 23, 2024
 Popular · Latest · Hot · Upcoming
61
rated 0 times [  64] [ 3]  / answers: 1 / hits: 17594  / 7 Years ago, tue, october 31, 2017, 12:00:00

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?


More From » function

 Answers
20

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)

[#56058] Friday, October 27, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
trentb

Total Points: 261
Total Questions: 101
Total Answers: 90

Location: French Southern and Antarctic Lands
Member since Fri, Jan 6, 2023
1 Year ago
trentb questions
Sat, Mar 27, 21, 00:00, 3 Years ago
Fri, Feb 26, 21, 00:00, 3 Years ago
Thu, Sep 24, 20, 00:00, 4 Years ago
;