Would using a global function like Object.keys() inside a pure function be reasonably considered an impurity?

212 views Asked by At

I'm currently going through my React project looking at where I can convert impure functions into pure functions in order to have less side effects, tidier and more understandable code.

I believe/hope converting to pure functions where possible will achieve this.

My question is, would using Object.keys() inside a function be considered an impurity?

Object.keys()

My thinking is that as although Object.keys() is a function that isn't within the getObjectKeys scope, it is global within vanilla JS and so it wouldn't be considered an impurity or need to be added to the function parameters in an effort to make the function pure by using Dependency Injection . So when asking if getObjectKeys is a pure function:

  • For the same input does it output the same -> yes.
  • Modifying any external variable or object property -> no
  • Are there any side effects -> no

Would you consider getObjectKeys a pure function?

function getObjectKeys(obj) {
    return Object.keys(obj)
}
1

There are 1 answers

5
Zazaeil On

It is (almost) pure. "Almost" because you assume that input gonna be an object and I think you can make it fail by feeding wrong input.

However, and it is indeed important, it is absolute nonsense to introduce

function getObjectKeys(obj) {
    return Object.keys(obj)
}

in your real codebase. It does not make any better, nor readable, nor maintainable. That's not what functional programming is all about.