DEV Community

Discussion on: Dealing with side effects and pure functions in javascript

Collapse
 
vonheikemen profile image
Heiker • Edited

I'd be happy to use it. It would be great because if one could mark a function as pure it would make it easier to isolate side effects to one part of the codebase, or at the very least keep a critical portion pure. I don't know to what extend javascript runtimes could benefit from something like that.

Nim (a programming language) has something like that. They have a way to indicate that a function should have no side effect: link. And in this hacker news thread (which I didn't read) people talk about that feature.

Collapse
 
kosich profile image
Kostia Palchyk • Edited

Nim is quite interesting, I haven't had a chance to dig deep into it yet. I'll check it out, thanks!

isolate side effects to one part of the codebase

Yeah! I think this is one of the big tricks we use for reasoning and composing our code: we move things to the edge. We separate "model" from "view", DB access from business logic, etc. To me pure function composition seems to be the essence of this approach.

I don't know to what extend javascript runtimes could benefit from something like that.

Alas, neither do I. In my uneducated view, engines could optimize -> code easier. Array methods run in parallel is something long-promised but not yet possible. Also maybe we could get automatic memoization of pure functions with garbage-collected caches.

Maybe JS libs could also do some optimizations if we had a method to distinguish pure from impure functions (isPureFunction or isImmutable && isFunction).


I think to test the idea we could imitate pure functions client-side a-la:

let PURE_SYMBOL = Symbol();

export function purify(fn) {
  fn = Function('a', 'return (' + fn.toString() + ')(a)'); // naive eradication of possible closure captures
  let result =
    x => isImmutable(x)
      ? fn(x)
      : throw 'Pure functions can be called only w/ immutable args';
  result[PURE_SYMBOL] = true;
  return Object.freeze(result);
}

export function isPure(fn) {
  return PURE_SYMBOL in fn;
}
Enter fullscreen mode Exit fullscreen mode

It's at least interesting to fantasize about it 🙂

P.S: someone shared with me a link to TS discussion on a related subject "add a modifier for pure functions" (haven't read it yet)