Curry

Haskell

Curry

Currying

Function

JavaScript Currying

And You're Teaching It Wrong!!

Alex Riviere

Senior Frontend Web Developer

blog: alex.party

mastodon: @fimion@notacult.social

bsky: @dangitalex.wtf

What is Currying?

\begin{aligned} &\text{let }x=f(a,b,c)\\ \\ &\text{gives }x\text{ the same value as the code:}\\ \\ &\text{let }h=g(a)\\ &\text{let }i=h(b)\\ &\text{let }x=i(c)\\ \\ &\text{or called in sequence,}\\ &\text{let }x=g(a)(b)(c) \end{aligned}

What is Currying?

Currying Functions are just

Scope Closures

What is Currying?

function addThree(a){
  return function(b){
    return function(c){
      return a+b+c;
    }
  }
}

addThree(1)(2)(3); // result: 6

Photo by Tom Dillon on Unsplash

Good

Bad

function addThree(a){
  return function(b){
    return function(c){
      return a+b+c;
    }
  }
}

addThree(1)(2)(3);

Currying as a Factory

Factory Method

A function that returns an object without having to define the type of that object.

Closure

When a function that is defined inside of a parent function is exposed outside of it's original scope, it has access to the inner scope of the original parent function.

Currying as a Factory

export const authFetchStuffFactory = (token) =>{
  const fetchStuffFactory = (url) =>{
    const fetchStuff = (options = {})=>{
      options.headers = {
        ...(options.headers||{}), 
        'Authorization':`Bearer ${token}`
      };
      return fetch(url, options);
    };
    return fetchStuff;
  };
  return fetchStuffFactory;
};

Currying as a Factory

Currying as a Factory

import {authFetchStuffFactory} from './my-library.js';

const token = 'my-very-secret-token';
const endpoint = '/api/my-secure-endpoint'

await authFetchStuffFactory(token)(endpoint)();

Currying as a Factory

// file: ./auth-fetch.js
import {authFetchStuffFactory} from './my-library.js';
import {getToken} from './auth-provider.js';

const authFetchFactory = authFetchStuffFactory(getToken());

export const fetchUsers = authFetchFactory('/api/users');
export const fetchReports = authFetchFactory('/api/reports');

Currying as a Factory

// file: my-component.jsx
import {fetchUsers} from './auth-fetch.js';

// ... somewhere in our component...
await fetchUsers();

Currying Functions

  • Don't use them for everything 
  • Do use them when you want to reuse some code
  • It's only a Currying Function if it is from the Currying region of mathematics, otherwise it is just ✨Sparkling Closures✨

Thank you

Alex Riviere

Senior Frontend Web Developer

blog: alex.party

mastodon: @fimion@notacult.social

bsky: @dangitalex.wtf

Currying - ThunderPlains 2023

By Alex Riviere

Currying - ThunderPlains 2023

  • 96