DEV Community

Hihi
Hihi

Posted on

Currying in Javascript

Currying in Javascript It can be understood as function caching. Consider the snippet below:

// utils.js

const submitForm = (formName: string) => (submittedFormData) => {
    const currentForm = getForm(formName);
    return submit = () => {
        validateForm(currentForm, submittedData)
        callSubmitFormAPI(submittedFormData)
    }
}
Enter fullscreen mode Exit fullscreen mode

Firstly, we gonna get the form object from formName; Let's say if we have multiple formData waiting for submission (with diffrerent submittedFormData), we can use this function and not having to re-call the getForm function to get the same form:

import { submitForm } from 'utils';

const registerForm1Data = { ...someFormData1 };
const registerForm2Data = { ...someFormData2 };

// return the function `submit` function
const formSubmission = submitForm('REGISTER_FORM'); 

if (user === isSomeFlag) {
    // can be seen as submitForm('REGISTER_FORM')(registerFormData1)
    formSubmission(registerFormData1) 
} else {
    formSubmission(registerFormData2)
}
Enter fullscreen mode Exit fullscreen mode

References:

Understand Currying - blogrocket;
Javascript Currying - javascript.info

Top comments (0)