I know this example is quite contrived but I am still curious wether or not this can be considered a pure function:
const addAsync = (x, y) => new Promise((resolve, reject) => {
setTimeout(
() => resolve(x + y),
Math.random() * 1000
);
});
Every call to this function returns a Promise that resolves to the sum of the two arguments. The promise resolves after a random amount of time between 0 and 1 seconds.
For all intends and purposes, this seems to be perfectly pure, meaning that I can treat this function in tests or in my code as a pure function (a, b) -> Promise(a + b)
. However, since we are using Math.random()
, we cannot transform this function into a lookup table and back without losing functionality (we lose the delay). So can this considered to be pure or not?
I believe it can be consider as a pure function. A pure function is defined as a function where the return value is only determined by its input values, without observable side effects.
In this case the output is only determined by its input and it doesn't produce any side effects. The fact that it takes different amount of time to compute the result should not have an effect on its pureness.
But i would warn that i am not a functional programming expert and i may be wrong
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With