Javascript | Currying VS Partial Application 2019 🎯🎯🎯

Javascript | Currying VS Partial Application 2019 🎯🎯🎯

A lot of people get confused in between currying and partial application and many of us does not know what, where and when we should use them. So this post will cover the practical usage and difference in them.

Originally published by DEEPAK GUPTA at overflowjs.com

So lets’s start with definitions

Currying

Is a technique for converting function calls with N arguments into chains of N function calls with a single argument for each function call.

Currying always returns another function with only one argument until all of the arguments have been applied. So, we just keep calling the returned function until we’ve exhausted all the arguments and the final value gets returned.

// Normal function
function addition(x, y) {
   return x + y;
}
// Curried function
function addition(x) {
   return function(y) {
     return x + y;
   }
}

Note: Curry takes a binary function and returns a unary function that returns a unary function. Its JavaScript code is

function curry(f) {
  return function(x) {
    return function(y) {
       return f(x, y);
    }
  }
}

Note: A curried functions have a built-in iterator behaviour. One argument is applied at once which is then returned to the calling function to be used for next step. Read here about iterators.

Usages

1.   The common use-case for curried function are function composition.e.g., p(x) = q(r(x)). i.e building new function from old function by passing arguments. Function q takes the return value as an argument from function r . Since a function can only return one value, the function being applied to the return value must be unary.

2.   Curried function can also be used while infrastructure setup of a project where there is a lot of possibility to create generic functions thereby little pieces can be configured and reused with ease, without clutter.

3.   Ramda.js lib. functions are automatically curried and lodash has a function called curry which can be used to form curry function.

4.   Memoization is another good use case for curry function.

5.   Handling error throwing functions and exiting immediately after an error.

6.   Catching multiple error and use it as a validator on API’s and client side code.

7.   Can create First class functions which means that we can use functions as arguments and return values. Eg:

const func1 = () => console.log ('Hey Medium.');
const firstClassfunc1 = argsFunc => argsFunc();
const firstClassfunc2 = () => func1;
firstClassfunc1 (firstClassfunc2()); // Hey Medium.

Curry Factory Method(ES6)

const compose = (...fns) =>
  fns.reduce((f, g) => (...args) => f(g(...args)));

Here is a good article on how to make our own curry function factory method using ES5.

Note: Currying in Javascript if not done properly can leads to more complicated stack traces, which is unfortunate for debugging.

Partial Application

Is a technique of fixing a number of arguments to a function, producing another function of smaller arguments i.e binding values to one or more of those arguments as the chain of function progressed.

function add1(x) {
  return 1 + x;
}

JavaScript has the built-in method .bind that works on functions with any number of arguments and can bind an arbitrary amount of parameters. Its invocation has the following syntax.

function.bind(thisValue, [arg1], [arg2], ...)

It turns function into a new function whose implicit this parameter is this value and whose initial arguments are always as given.

function addition(x, y) {
   return x + y;
}
const plus5 = addition.bind(null, 5)
plus5(10) // output -> 15
Note: this value does not matter for the (non-method) function addition which is why it is null above.

When using underscore or lodash you can use the partial function which is much nicer than the raw bind method.

Here is a detailed post on partial application and left, right partial application function implementation.

Difference

  • Currying always produces nested unary (1-ary) functions. The transformed function is still largely the same as the original.
  • Partial application produces functions of arbitrary number of arguments. The transformed function is different from the original β€” it needs less arguments.
  • Currying is not partial application. It can be implemented using partial application. You can’t curry a function that takes any number of arguments, (unless you fix the number of arguments).

Advantages

Easier reuse of more abstract functions which leads to clean code and less complexity which improves code expressive power and maintainability.

If anything is not clear or you want to point out something, please comment down below.

Thanks and Stay tuned for more!


Originally published by DEEPAK GUPTA at overflowjs.com

===========================================

Thanks for reading :heart: If you liked this post, share it with all of your programming buddies! Follow me on Facebook | Twitter

Learn More

☞ Svelte.js - The Complete Guide

☞ The Complete JavaScript Course 2019: Build Real Projects!

☞ Become a JavaScript developer - Learn (React, Node,Angular)

☞ JavaScript: Understanding the Weird Parts

☞ JavaScript: Coding Challenges Bootcamp - 2019

☞ The Complete Node.js Developer Course (3rd Edition)

☞ Angular & NodeJS - The MEAN Stack Guide

☞ NodeJS - The Complete Guide (incl. MVC, REST APIs, GraphQL)

☞ Node.js Absolute Beginners Guide - Learn Node From Scratch


javascript web-development

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Hire Web Developer

Looking for an attractive & user-friendly web developer? HourlyDeveloper.io, a leading web, and mobile app development company, offers web developers for hire through flexible engagement models. You can **[Hire Web...

Why Web Development is Important for your Business

With the rapid development in technology, the old ways to do business have changed completely. A lot more advanced and developed ways are ...

Important Reasons to Hire a Professional Web Development Company

Β  Β  You name the business and I will tell you how web development can help you promote your business. If it is a startup or you seeking some...

Hire Dedicated eCommerce Web Developers | Top eCommerce Web Designers

Build your eCommerce project by hiring our expert eCommerce Website developers. Our Dedicated Web Designers develop powerful & robust website in a short span of time.

How long does it take to develop/build an app?

This article covers A-Z about the mobile and web app development process and answers your question on how long does it take to develop/build an app.