Does a function that receives a function as a parameter can still be considered a pure function?

Viewed 95

is addVat a pure function?

function addVat(country, getVat, amount)
{
   if(amount > 0) {
     return amount + getVat(country)*amount
   }
   
   return amount
}

Having a function as a parameter - getVat - makes addVat automatically impure?

Depending on the implementation of getVat, we could introduce any side effects... getVat could return a random value making the result of addVat unpredictable.

const getVat = ()=> Math.random()
addVat('UK',getVat, 20)

Case of producing external side-effects...

const getVat = ()=> {
  updateDbWithVatUsed(0.2)
  return 0.2
}
addVat('UK',getVat, 20)

By other hand, the unit testing is feasible as side effects or data variability is outside of the pure function and we can stub this to make testing totally predictable.

const getUKVat = ()=> 0.2
assert.equal(addVat('UK',getUkVat, 20), 24)

My doubts come from... is purity defined as what the function does excluding anything what happens to an external call that has been passed as a parameter?

Otherwise, as high order function is a theme for Functional programming... does it not make it impossible to classify a function as pure just by itself without considering invocation considerations.

2 Answers

I think it depends on getVat(). If getVat() is pure addVat() is pure too :)

Javascript language does not enforce purity, and hence it's impossible to guarantee purity of a function which invokes functions passed as arguments. This thread might help.

Related