DEV Community

Cover image for Functional Programming: an accumulator of methods to transform objects in Javascript
Sergio Matone
Sergio Matone

Posted on

Functional Programming: an accumulator of methods to transform objects in Javascript

While I was trying to solve a problem within my code, I had to modify an object by applying a set of transforming methods. I had to do the same with a whole array of strings, all requesting the same set of transformers to be applied.

Since I am a big fan of Functional Programming I wanted to use a map-reduce approach. I came up with a generic method leveraging the native reduce method of Array objects, the idea is to “accumulate” a string which at each iteration becomes both the result of the last transformation method and the input for the next transformation method.

Here is a placeholder:

const tranformers = [s => s.trim(), s => s.toUpperCase()];

const multiTransform = (str) => tranformers.reduce(
  (accumulator, currentValue) => {
    return currentValue(accumulator);
  },  // reduce callback
  str // initial value
);

console.log("Expecting the value 'HELLO WORLD' from `multiTransform` method:", multiTransform(" hello world "));
Enter fullscreen mode Exit fullscreen mode

And in order to show how it can be applied to a set of strings, I will leverage the brand new Node.js Native Test Runner, which is still experimental but can be used from versions of Node.js >= v18.0.0 LTS (or either v16.17.0):

import assert from 'node:assert';
import test from 'node:test';

test('array transformation', (t) => {
  const arr = [" alice ","bob"," paul"];
  assert.deepEqual(["ALICE","BOB","PAUL"], arr.map(multiTransform));
});

---
>  array transformation (1.886ms)
Enter fullscreen mode Exit fullscreen mode

In vanilla Javascript, soon everything can become a mess due to the nature of the language, which is weakly typed. So the idea behind this accumulator pattern is to apply a certain number of transformations to a set of homogeneous objects; Strings are the most straightforward example of course.
Another possibility is that transformation methods include the capability to receive different object types and transform them according to the type of the object itself.

Top comments (0)