JavaScript
  • JavaScript Introduction
  • JS Engine
  • V8 Engine
  • First-class function
  • Optimized Code
  • Call Stack & Memory heap
  • Single Thread
  • JavaScript RunTime
  • Nodejs
  • Context and Environment
  • Hoisting
  • Functions
  • Arguments
  • Variables
  • Scope
  • IIFE
  • this
  • call(), apply() and bind()
  • currying
  • Types
  • Type Coercion
  • Functions as Object
  • HOF (Higher Order Function)
  • Two pillars of Javascript
  • Closures
  • Prototypal Inheritance
  • OOP and FP
  • OOP
    • 4 principles of OOP
  • FP
    • Pure function
    • Imperative vs Declarative
    • Immutability
    • HOF and Closures
    • Currying
    • Partial Application
    • Compose and Pipe
  • Composition vs Inheritance
  • OOP vs FP
  • JS working
  • Promises
  • Async Await
  • ES5 - ECMAScript 2009
  • ES6 - ECMAScript 2015
  • ES7 - ECMAScript 2016
  • ES8 - ECMAScript 2017
  • ES9 - ECMAScript 2018
  • ES10 - ECMAScript 2019
  • ES11 - ECMAScript 2020
  • ES12 - ECMAScript 2021
  • JOB Queue
  • Promises Execution
Powered by GitBook
On this page

Was this helpful?

currying

Currying is a transformation of functions that translates a function from callable as f(a, b, c) into callable as f(a)(b)(c).

  • we can transform a function with multiple arguments into a sequence of nesting functions.

  • It returns a new function that expects the next argument inline.

  • It keeps returning a new function (that expects the current argument, like we said earlier) until all the arguments are exhausted.

  • The arguments are kept "alive"(via closure) and all are used in execution when the final function in the currying chain is returned and executed.

function curry(f) { // curry(f) does the currying transform
  return function(a) {
    return function(b) {
      return f(a, b);
    };
  };
}

// usage
function sum(a, b) {
  return a + b;
}

let carriedSum = curry(sum);

carriedSum(1)(2); // 3

Example Description:

  • The result of curry(func) is a wrapper function(a).

  • When it is called like carriedSum(1), the argument is saved in the Lexical Environment, and a new wrapper is returned function(b).

  • Then carriedSum(1)(2) finally calls function(b) providing 2, and it passes the call to the original multi-argument sum.

Advanced currying:

function addCurry(x) {
  return function innrFn(y) {
    if (y !== undefined) {
      x += y;
      return innrFn;
    } else {
      return x;
    }
  }
}

addCurry(1)(2) // [Function: innrFn]
addCurry(1)(2)(); // 3
addCurry(1)(2)(3)(); // 6
  • when the function call is completed with argument will return the function.

  • when function is call is completed without argument will return the sum of all arguments.

Previouscall(), apply() and bind()NextTypes

Last updated 5 years ago

Was this helpful?