DEV Community

Sam Clark
Sam Clark

Posted on

4 1

Arity In Functional Javascript

Good References:

I think most of the time it's easier for me atleast to read someone else's code instead of long drawn out blog posts. Let's take a look at this non-functional JS snippet:


function nfMultiply(a, b, c) {
  return a * b * c;
}

console.log('non-functional', nfMultiply(1, 2, 3));

Arity in essence is the number of functions you can pass into an object. It's all rather confusing, but i think of it as the amount of functions you can curry into one function, let's convert the function above into an arity of 3.

function multiply(a) {
  return b => {
    return c => {
      return a * b * c;
    };
  };
}

console.log('arity breakdown', multiply(1)(2)(3));

If you think about it simply how many times can i fold this function against itself. This becomes useful when we start creating more complex functional javascript statements(I really enjoy using lodash in my node code, and also because it's included in AWS lambdas by default, thus not really bloating it.):

More Advanced

const { has } = require('lodash');

const fakeDataFunc = () => 3;
const fakeObjFunc = () => ({ uncool: 'blue' });

function coolDude(a) {
  return b => {
    return c => {
      return d => {
        return e => {
          return {
            a,
            bTimesC: b * c(),
            d,
            eHas: has(e(), 'cool') ? 'sure does' : 'nope',
          };
        };
      };
    };
  };
}

console.log(
  'testing',
  coolDude('Mutliplied Value times a function is: ')(2)(fakeDataFunc)(
    'and here we generate a ternary if something is in an object:',
  )(fakeObjFunc),
);

You can take the above snippets and kind of meld them to your wishes, and play with them to create Higher Order Functions, enjoy!!!

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs