Function reusability with currying and partial applied in Javascript
Function reusability with currying and partial applied in Javascript

Function reusability with currying and partial applied in Javascript

Both partial application and currying are functional programming concepts that involve transforming functions to create new functions with specific behaviors. However, they achieve this in different ways:

  1. Partial Applied Function:

  • Partial application involves fixing a certain number of arguments of a function, creating a new function with the fixed arguments, and leaving the rest of the arguments to be provided later.
  • The resulting partially applied function takes fewer arguments than the original function.
  • You apply the arguments from left to right, and each argument is “partially applied” to the function.
  • The order of fixed arguments matters. The leftmost arguments are the ones that are fixed first.
  • You can create a partially applied function using a separate function (like in your example).


function multiply(a, b) 
  return a * b;
}

function partial(func, ...args) {
  return func(...args);
}

const double = partial(multiply, 2);
double(5); // Result: 10
double(20); // Result: 40        

  1. Currying Function:

  • Currying takes multiple arguments into a series of functions. Each function takes one argument and returns another function that takes the next argument until all the arguments are provided and the final result is returned.
  • The resulting functions take one argument at a time, and you need to chain these functions to obtain the final result.
  • The order of function chaining matters. The order in which you pass the arguments determines the final result.

function multiply(a, b) 
  return a * b;
}

const currying = (func) => (arg1) => (arg2) => {
  return func(arg1, arg2);
};

const double = currying(multiply)(2);
double(5); // Result: 10
double(20); // Result: 40        

In summary, partial application fixes some arguments to create a new function, reducing the number of arguments, while currying transforms a function to take one argument at a time, returning new functions in a chain until all arguments are provided. Both concepts are powerful techniques in functional programming like javascript and can be used based on the specific requirements of your code.

To view or add a comment, sign in

Others also viewed

Explore content categories