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

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

提交回复
热议问题