New package: pure-mutation

There’s one thing from the vastness of functional programming, which I made almost a rule - pure functions. What is a pure function? It’s a function that always returns the same output for the same arguments it received. Also, it should be free from making any side-effects (i.e., changing value by-reference).

I try to stick to this rule whenever it makes sense to do so. Eventually, I have a set of functions that I use in multiple places.

There are, however, some limitations. Here I’m talking about vendor libraries, which sometimes rely on state mutation. A good example here are pre hooks that can be used in Mongoose.

schema.pre('init', (doc) => {      
    delete doc.password
})

The library doesn’t use the output of the callback function - it has to mutate the given object. In this case, you can’t use a pure function, as it won’t have any effect. For me this would result in making another set of non-pure functions that should handle data by-reference. I’d rather avoid it.

So, I made @baethon/pure-mutation - a simple package that uses a pure function to mutate an object. With it, the previous example would look like this:

const  { unpure } = require('@baethon/pure-mutation')

schema.pre('init', unpure(({ password, ...data }) => data))

combined with Ramda:

const { unpure } = require('@baethon/pure-mutation')
const { omit } = require('ramda')

schema.pre('init', unpure(omit(['password'])))

Neat right? Although I know that there are not many use cases for this package, yet I’m excited to use it in next project. You can find the package on Github. Hope you’ll like it too.