Best Ways to Improving Javascript Functional Programming With Polyethylene

If you’ve worked with Javascript and arrays, you’ve surely used some of the functional utilities packed with them: filter, map, reduce and others. They’re incredibly useful tools in a ton of situations, but come with a few notable drawbacks:

  • Every call to a functional method returns a new Array. This creates unnecessary intermediate arrays, wasting time and memory.
  • These utilities are only available for Arrays. This wasn’t a problem a few years ago, but with the introduction of Symbol.iterator and for…of it’s now insufficient.
  • There is no support whatsoever for asynchronous operations. No callbacks, no promises, no events, no nothing: Your code must be sync and your data must be already in memory.

Thanks to for..of we can solve all of these issues by kind of re-implementing the methods ourselves, catered to each situation, but that defeats the point of having functional utilities in the first place. What can we do?

Here comes Polyethylene to the rescue. Polyethylene can solve all of the above problems, and a few more you didn’t know you had. Let’s see how one by one, and I’ll expand later.

But first, a disclaimer: I am the author of Polyethylene, so take everything I say here with that in mind.

Also, all code you’ll see here will assume you are importing Polyethylene as follows:

const Poly = require('polyethylene');

That’s all you need to know, let’s get to business!

Saving on Array copies

As Polyethylene objects are pure generators, no time or space will be spent in storing intermediate results of a chain of functional calls. This can make long arrays much faster to process.

Let’s use an example. Let’s say we have a list with peoples names, country codes, and ages. We want to find out the average age of those living in Spain:

const people = [{name: 'Dani', country: 'ES', age: 27}, /* more people */];

const {age, num} = people
  .filter(person => person.country === 'ES') // filter by country
  .map(person => person.age) // we're only interested in their age
  .reduce( // find total age and number of people
    (acc, age) => ({age: acc.age + age, num: acc.num + 1}),
    {age: 0, num: 0}
  );

const avgAge = age / num; // we have the average now!
PrevNext

Leave a Reply

Your email address will not be published. Required fields are marked *