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

后端 未结 9 1587
[愿得一人]
[愿得一人] 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)
    
    0 讨论(0)
  • 2021-01-30 16:16

    No, it isn't. You can't figure out the result at all, so this piece of code can't be tested. To make that code testable, you need to extract the component that generates the random number:

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

    Now, you can mock the generator and test your code properly:

    const result = test(1, 2, () => 3);
    result == 4 //always true
    

    And in your "production" code:

    const result = test(1, 2, Math.random);
    
    0 讨论(0)
  • 2021-01-30 16:19

    No, it isn't a pure function because its output doesn't depend only on the input provided (Math.random() can output any value), while pure functions should always output the same value for same inputs.

    If a function is pure, it's safe to optimize away multiple calls with the same inputs and just reuse the result of an earlier call.

    P.S for me at least and for many others, redux made the term pure function popular. Straight from the redux docs:

    Things you should never do inside a reducer:

    • Mutate its arguments;

    • Perform side effects like API calls and routing transitions;

    • Call non-pure functions, e.g. Date.now() or Math.random().

    0 讨论(0)
提交回复
热议问题