DEV Community

loading...

Discussion on: Pure vs Impure Functions

Collapse
eecolor profile image
EECOLOR

There are a few use cases where an implementation of a function could be considered 'not pure' while, from the outside, it is pure.

let complexValue = null
export function getComplexValue() {
  return complexValue || (complexValue = calculateComplexValue())
}

function calculateComplexValue() {
  // this is always the same
  ...
  return ...
}
Enter fullscreen mode Exit fullscreen mode
export function mapValues(o, f) {
   return Object.entries(o).reduce(
    (result, [k, v]) => (result[k] = f(v, k, o), result),
    {}
  )
}
Enter fullscreen mode Exit fullscreen mode