Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a pure function return a promise that resolves after a random amount of time?

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?

like image 920
basilikum Avatar asked Mar 07 '23 19:03

basilikum


1 Answers

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

like image 87
Jiby Jose Avatar answered Mar 12 '23 20:03

Jiby Jose