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

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

提交回复
热议问题