Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save nishantmendiratta/ae2fa85f8a37d6dbfa116fc128ddf834 to your computer and use it in GitHub Desktop.
Save nishantmendiratta/ae2fa85f8a37d6dbfa116fc128ddf834 to your computer and use it in GitHub Desktop.
sum(1)(2)(3)(4)..( n)() Frontend Javascript Interview Question
Credits

Visit Akshay Saini's YT channel for full video tutorial.


Can you write code for this function: sum(a)(b)(c)....( n)(). This should return the sum of all the numbers a+b+c+..+n.


// Functions in javascripts are First Class Functions
// Functions are like objects
// sum(1)(2)(3).. (n)

// Fist consider it like a function sum(1)(2)() which is called and gives output 3
let sum = function (a) {
  // Sum again gives a function which can be executed by passing an argument inside it let's call it b
  return function (b) {
	  return a+b
  }
}

// Now consider it like a function sum(1)(2)(3)() which is called and gives output 6
let sum = function (a) {
  return function (b) {
    return function (c) {
      return a+b+c;
    }
  }
}


// We can see a clear pattern, will solve it recursively
const sum  = function (a) {
  return function (b) {
    if (b) {
      return sum(a+b); // it takes an argument and return a function which again can take an argument.
    }
    return a; // it will keep on adding 1+2+3+4..
  }
};


console.log(sum(1)(2)()); //3
console.log(sum(1)(2)(3)(4)()); //10

Subscribe

Subscribe to the newsletter.


Bookmark

Unlike life, keyboards do have shortcuts, press COMMAND+D to make this an easily accessible resource by bookmarking it.

@Rameshwar-ghodke
Copy link

after trying same code, showing error - Uncaught TypeError: sum(...)(...)(...) is not a function
at :9:25

@nishantmendiratta
Copy link
Author

@Rameshwar-ghodke Following code works fine.

const sum  = function (a) {
  return function (b) {
    if (b) {
      return sum(a+b); // it takes an argument and return a function which again can take an argument.
    }
    return a; // it will keep on adding 1+2+3+4..
  }
};


console.log(sum(1)(2)()); //3

@krishnakumarsingh
Copy link

krishnakumarsingh commented Apr 22, 2024

const sum = a => b => b ? sum(a+b) : a;
console.log(sum(1)(2)(3)());

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment