you have made videos on such interesting topics that I had to finish them in one sitting . My friends actually thought I was watching some movie. Great vids and explanation especially for a js newbie. keep them coming. I want that bell icon to ring a lot. :)
tip: input sum(1)(2)(0)(3)(4)(5)() and watch it blow up ... use typeof to check the existence of b, because 0 is falsy and it won't return a function to be called in the next step, resulting in "TypeError: sum(...)(...)(...) is not a function" const sum = (a) => (b) => (typeof b === "undefined" ? a : sum(a + b));
This function missing a corner case. If one of the arguments is zero(0) then the functionality will break. we can fix it just by doing a check like *b !== undefined*
That's an awesome video. I guess your solution will return a function. Eg: consol.log(sum(2)(3)(4)) => return a function and prints the same. To print the sum we can use: const addAll = sum(2)(3)(4); console.log(addAll());
It returns a function if you do this console.log(sum(1)(2)(3)(4)(5)); But when you pass an empty argument in the same line at the end it will give you the correct output, like this: console.log(sum(1)(2)(3)(4)(5)());
Hey Akshay, Your way of explaining things make everything very simple. The most interseting part is your way of linking everything with simple examples. Can you make one video over Promise, obeservables and async/await?
I saw the question and tried the code myself.. This is what i came up with after 10mins of struggle: let sum=(x=null)=>{ if(x===null) return 0 let acc=x return function f(y=null){ if(y===null) return acc acc+=y return f } } sum(10)(20)(30)() //60 sum() //0 sum(0)(0)() //0 i was so happy that it works.. Then saw your simple beautiful solution and now i am depressed
Before watching the video and seeing your solution, I tried it as an exercise. Here's my answer: function weirdSum(a) { if(typeof a === 'number') { return function (b) { if(typeof b === 'number') return weirdSum(a + b); else return a; } } return a; } It's more verbose, but I think it's pretty clear. I love how recursion and closures are playing so well together here.
I have been asked the same question in interview...i was searching the solution on internet. not found anywhere but .....got here....Thanks a lot Akshay...
Hi Akshay, I did it with a different approach, but of course your solution is cleaner. function sum(val) { if (val === void 0) { if (sum.previousValues) sum.previousValues.push(val) else sum.previousValues = [val] return sum; } else { const previousValues = sum.previousValues || [] // for handling sum() scenario sum.previousValues = null return previousValues.reduce((acc, elem) => acc + elem, 0) } }
Hey Akshay, thank you for providing a good youtube video on Frontend Javascript interview question. I modify your code to remove the error ocuring in case of sum(10)(10)(0)(40)(). so the solution is let sum = a => b => (b || (b==0)) ? sum(a+b) : a; console.log(sum(10)(10)(0)(40)());
The code requires a little bit of adjustment. If one of the arguments in the middle is zero then it will result in an error because the inner function returns the overall result, then attempts to call a function on a non fuction expression. I'm not sure if this problem is mentioned in the video and intentionally excluded because I just quickly checked the final code. :) This would I think fix the issue: const add = a => b => !isNaN(b) ? add(a + b) : a
Good catch Daniel. But the main objective of the video was to explain how to attempt this question and and walkthrough the solution by recursively calling the functions. Just a generic approach, the function here could be add, multiply or xyz and corner cases for each will be different. But yeah, I second you. We should add validations for the arguments in all the cases to handle such corner cases :)
If I call your sum function like this sum(1)(3)(0)(2)(), it fails. Basically calling your function with parameter 0 causes error. To rectify this issue you need to write your if statement inside the nested function like this. if(b != undefined) or if(arguments.length>0). Second one will not obviously work with arrow functions.
Yes, I got a similar comment earlier also, Bharat. But the main objective of the video was to explain how to attempt this question and and walkthrough the solution by recursively calling the functions. Just a generic approach, the function here could be add, multiply or xyz and corner cases for each will be different. But yeah, I second you. We should add validations for the arguments in all the cases to handle such corner cases :) Again, Thanks for pointing out. Next time I'll try to cover these small things as well.
Thanks to you akshay, trying all these questions out to learn better. generic way to do the above for any 2 arg function Function.prototype.curry = function(){ const funcToCurry = this; return function curr(a){ return (b)=> b !== undefined ? curr(funcToCurry(a,b)):a; } } function sum(a,b){return a+b;} var curriedSum = sum.curry(); console.log(curriedSum(4)(5)(3)(8)());
Right solution for the first problem where sum(a)(b)() gives us a+b function sum(a){ return function(b){ return function() { return a + b } } } @akshay love your videos.
Veer, I think this one is the best article about Generator function: codeburst.io/understanding-generators-in-es6-javascript-with-examples-6728834016d5 Message me if you think you need a more in-depth understanding.
U explain in such an amazing way that js becomes really easy to understand..before watching your videos , I w asjust learning but not enjoying....Now it's been 3 hours I am learning while watching your videos and seems like I am not studying now but just enjoying every bit of the learning time... thanks alot...keep doing this good work...excited to see more related to react and node.js as well...god bless you 😊
for python developers this can be achieved like this: class SUM: val = 0 def __init__(self, val): self.val += val def __call__(self, val): self.val += val return self def __str__(self): return str(self.val) print(SUM(1)(2)(3)(4)(5)(6)) #21
I think under the arrow function you don't need a return statement instead of that simply right; let sum = a => b => b ? sum(a+b) : a; console.log(sum(4)(5)(2)());
Thanks a lot Akshay, for all your efforts in making these videos it has helped me and many others to crack the interviews. I am really grateful to you. 🙏😊
Sir can you please create a detailed video with a lot of example of currying function, please? I know you have already a video on the topic and I watched that. But somehow I feel like you can make it awesome.
Wow, that was a 1 line code , Liked it :) (y). This was the one which I arrived at : function sum(currentTotal) { if(!currentTotal) return 0; return function(num) { if(!num) return currentTotal; return sum(currentTotal + num); } }
To support variadric functions: const add = (...a) => (...b) => b.length ? add(...a, ...b) : a.reduce((a, b) => a + b, 0); add(1,2)(3,4)(5)(); // 15 Using an empty parameter invocation as a terminator seems a little bit janky in practical usage. It's probably great to override the returning functions valueOf() as a way to generate the value. Although a bit lengthy: const add = (...a) => { const $add = (...b) => { a = a.concat(b); return $add; } $add.valueOf = () => a.reduce((x,y) => x + y, 0); return $add; } +add(1)(2,3)(4,5); //15 Note the usage of the unary '+' operator as a means to get the primitive value of the function. source: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/valueOf
Hello, I really liked the video, you explained in detail. Can you also explain how instead of sum which we do inside the function , how we can apply the function which was passed as an argument
nice description, thx. but how about situations, when call simple sum(1,5) or call sum(1)(2) without () on the end? maybe change function, witch can pass thus case
very good job Akshay....please keep it continue ...it is very helpful..... Can you please give an understanding for my question... I was asked a this question when I was hunting job, that was balance the string with braces for an example "{a}[b]{c:[c]}" if a kind of braces start it should properly close.
Yeah, sure. This is also a very common question asked in the interviews. I've myself faced it. Give me some time I'll surely come up with that. 😊 And glad that you liked the video, your compliments make me work more hard and come up with something better everytime to help everyone. Thanks. 😊
Akshay in this example it will return correct output for sum(1)(2)(3)(4)(). But how we will write the code for this sum(1)(2)(3)(4) and output should be 10. I tried and I am getting function as return value. Can we do that or not?
Hi Akshay... I just got an offer as fresher from a company in Bangalore and they asked this question, I was not able to answer but I answered other questions, I explained concepts as you did, they were impressed. your videos helped me a lot to reach there. Thanks a lot. and I would like to dedicate my first salary to a few of my UA-cam gurus, and you also one among them. kindly let me know how can I support you.
I was asked this question in an interview today and my bad I wasn't able to crack it as I didn't come across this video before. Hope I'll crack it in future interviews.
We can also use an arrow function and take all the argument and pass it one by one, for ex: const fun = (a)=>(b)=> { // Code here } Correct me if I'm wrong
Hi Akash,first of all i would like to thank for kind of knowledge you are sharing through your videos.i have faced question about web page optimization in many interview,can you make good video on that.it will be really good knowledge to share i think.
function sum(num, total = 0) { if(num === undefined) { return total } return (newNum) => sum(newNum, total + num) } This is what I implemented before checking the solution.
Hi Akshay. Being a front end developer, I've faced similar questions while on job hunt. Your videos are extremely informative and helpful and I am sure it'd definitely help job seekers out there. Keep up the good work. I hope to see more contents. I've a small request for you. A video on javascript design patterns and how different libraries use them under the hood might come in handy somedays.
Let sum = a=> b=> return b? Sum(a+b) : a will have an error. I believe we need to put the return statement in {} or else we can completely omit the return. It will still work.
Hi Akshay , This was good and detailed information on sum(1)(2)(3)() . I have few queries , suppose if the last() is not given and we are still asked to return sum , how can we achieve it ?
if the last() is not given and we are still asked to return sum, assign the function output to a variable and console log it const addAll = sum(2)(3)(4); console.log(addAll());
I've made use of debounce here :) const sum = (function(){ let total = 0; let timer; function display(total){ clearTimeout(timer); timer = setTimeout(function(){ console.log(total); }, 0); } return function(num){ total += num; display(total); return sum; } })();
hi akshay , i love watching your videos , they are really informative , i have a request , can you make a video on asynchronous js , and important features in CSS
Hi akshay i am sure u have faced many frontend interview, i just wanted to know have u ever been asked system design question specific to frontend if yes can you please make some video on that
let arr=[1,2,8,2,1,3,6,7]; let obj={}; for(let i of arr){ obj[i]=true; } console.log(obj); let b=Object.keys(obj); console.log(b); the above code is to remove duplicate from array, i didn't understand the flow inside the for loop. pls can u explain.
here obj is working as a HashMap support 1 1 2 2 3 3 are your elements so obj is basically counting the occurrence of each element and then for the unique element you are just printing the keys of the hashMap i.e obj after for loop you obj will be like { 1:2, 2:2, 3:3 } see above keys are 1,2,3 and following colon are their occurrences in array and its pretty clear that keys will always give unique elements Hope you understood it
@akshay: there is a variant of this question in which we have to write a function which will give same output to these two invocations 1) sum(1)(2)(3)....() 2) sum(1,2,3....) Can you make a video for how to approach this question? Thanks in advance
3:10 sum(1)(2)() = 3 var sum = function (a){ return function(b){ return a + b; } } it will not return 3 but a error : VM473:6 Uncaught TypeError: sum(...)(...) is not a function
you have made videos on such interesting topics that I had to finish them in one sitting . My friends actually thought I was watching some movie. Great vids and explanation especially for a js newbie. keep them coming. I want that bell icon to ring a lot. :)
tip: input sum(1)(2)(0)(3)(4)(5)() and watch it blow up ... use typeof to check the existence of b, because 0 is falsy and it won't return a function to be called in the next step, resulting in
"TypeError: sum(...)(...)(...) is not a function"
const sum = (a) => (b) => (typeof b === "undefined" ? a : sum(a + b));
This was useful, thank you :)
useful
This function missing a corner case. If one of the arguments is zero(0) then the functionality will break. we can fix it just by doing a check like *b !== undefined*
...or check if(arguments.length)
@@maratzakaryan1310 arguments.length wont work with fat arrow functions
Or we can preset (params=0)
Just look at the transformation of Akshay between this series and the namaste javascript series. How much he has changed 🔥.
That's an awesome video. I guess your solution will return a function.
Eg: consol.log(sum(2)(3)(4)) => return a function and prints the same.
To print the sum we can use:
const addAll = sum(2)(3)(4);
console.log(addAll());
It returns a function if you do this
console.log(sum(1)(2)(3)(4)(5));
But when you pass an empty argument in the same line at the end it will give you the correct output, like this:
console.log(sum(1)(2)(3)(4)(5)());
Man you are really very honestly giving all the knowledge with all the innocence. Really appreciate your effort.
Hey Akshay, Your way of explaining things make everything very simple. The most interseting part is your way of linking everything with simple examples. Can you make one video over Promise, obeservables and async/await?
I saw the question and tried the code myself.. This is what i came up with after 10mins of struggle:
let sum=(x=null)=>{
if(x===null)
return 0
let acc=x
return function f(y=null){
if(y===null)
return acc
acc+=y
return f
}
}
sum(10)(20)(30)() //60
sum() //0
sum(0)(0)() //0
i was so happy that it works.. Then saw your simple beautiful solution and now i am depressed
Before watching the video and seeing your solution, I tried it as an exercise. Here's my answer:
function weirdSum(a) {
if(typeof a === 'number') {
return function (b) {
if(typeof b === 'number') return weirdSum(a + b);
else return a;
}
} return a;
}
It's more verbose, but I think it's pretty clear. I love how recursion and closures are playing so well together here.
I have been asked the same question in interview...i was searching the solution on internet. not found anywhere but .....got here....Thanks a lot Akshay...
Hi Akshay, I did it with a different approach, but of course your solution is cleaner.
function sum(val) {
if (val === void 0) {
if (sum.previousValues)
sum.previousValues.push(val)
else
sum.previousValues = [val]
return sum;
} else {
const previousValues = sum.previousValues || [] // for handling sum() scenario
sum.previousValues = null
return previousValues.reduce((acc, elem) => acc + elem, 0)
}
}
I was not able to solve it in an interview and was not short listed for next round, thanks for explanation
Hey Akshay, thank you for providing a good youtube video on Frontend Javascript interview question. I modify your code to remove the error ocuring in case of sum(10)(10)(0)(40)(). so the solution is
let sum = a => b => (b || (b==0)) ? sum(a+b) : a;
console.log(sum(10)(10)(0)(40)());
Could also modify it to include passing in strings, null values, etc. Clarifying questions are important before you start writing code :)
The code requires a little bit of adjustment. If one of the arguments in the middle is zero then it will result in an error because the inner function returns the overall result, then attempts to call a function on a non fuction expression. I'm not sure if this problem is mentioned in the video and intentionally excluded because I just quickly checked the final code. :)
This would I think fix the issue: const add = a => b => !isNaN(b) ? add(a + b) : a
Good catch Daniel. But the main objective of the video was to explain how to attempt this question and and walkthrough the solution by recursively calling the functions. Just a generic approach, the function here could be add, multiply or xyz and corner cases for each will be different. But yeah, I second you. We should add validations for the arguments in all the cases to handle such corner cases :)
@@akshaymarch7 you can replace the if(b) condition with if(arguments.length) to solve this error
@@pranaysharma7119 Yes, you're right.
You should check b if it is undefined. This will fix the 0 argument problem ... var sum = (a) => (b) => b == undefined ? a : sum(a + b)
If I call your sum function like this sum(1)(3)(0)(2)(), it fails. Basically calling your function with parameter 0 causes error. To rectify this issue you need to write your if statement inside the nested function like this. if(b != undefined) or if(arguments.length>0). Second one will not obviously work with arrow functions.
Yes, I got a similar comment earlier also, Bharat.
But the main objective of the video was to explain how to attempt this question and and walkthrough the solution by recursively calling the functions. Just a generic approach, the function here could be add, multiply or xyz and corner cases for each will be different. But yeah, I second you. We should add validations for the arguments in all the cases to handle such corner cases :)
Again, Thanks for pointing out. Next time I'll try to cover these small things as well.
was asked this same question in recent interview, which ofcourse I nailed thanks to you Akshay
Thanks to you akshay, trying all these questions out to learn better.
generic way to do the above for any 2 arg function
Function.prototype.curry = function(){
const funcToCurry = this;
return function curr(a){
return (b)=> b !== undefined ? curr(funcToCurry(a,b)):a;
}
}
function sum(a,b){return a+b;}
var curriedSum = sum.curry();
console.log(curriedSum(4)(5)(3)(8)());
I was confused with the function,but now am happy.
9:21 why if we do sum(1)(2) and the next argument (3) is reffering to b in sum(a, b)? why a is not the argument(3) in the sum(a,b) after sum(1)(2)(3)?
Right solution for the first problem where sum(a)(b)() gives us a+b
function sum(a){
return function(b){
return function() {
return a + b
}
}
}
@akshay love your videos.
best java script teacher
Simply awesome.... just love it as your explanation
Hey Akshay, can you please upload a video explaining Generator function in detail. This is being used at many places and I am not confident on it.
Veer, I think this one is the best article about Generator function: codeburst.io/understanding-generators-in-es6-javascript-with-examples-6728834016d5
Message me if you think you need a more in-depth understanding.
That's called "Currying" in JS.
U explain in such an amazing way that js becomes really easy to understand..before watching your videos , I w asjust learning but not enjoying....Now it's been 3 hours I am learning while watching your videos and seems like I am not studying now but just enjoying every bit of the learning time... thanks alot...keep doing this good work...excited to see more related to react and node.js as well...god bless you 😊
Thank you for the clear explanation! It was so helpful to see different variations too!
When I used to go for interview in 2012 to 2014 I always wonder why I never encountered such situation while coding for projects 😀
for python developer :
😁😁😁😁
def f(a):
def f(b=False):
if b:
return sum(a+b)
return a
return f
sum=f
print((sum(1)(2)(3)(10)()))
😅😅😅😅😅😅
Thank you so much dude. Everything is clear to me. Your videos make my foundation in JS better.
wow... you made my day... great explanation on recursive function. Thankyou
another implementation
var sum = function(x, acc){
if(acc == undefined) acc = x;
return function(y){
if(y == undefined) return acc;
return sum(y, acc + y);
}
}
Thank You Akshay! Your videos are very important and best for Frontend Engineering positions
thankyou so much Akshay Sir, Amazing Amazing explanation of recursion!!
The shortest answer:
const sum = x => y => y === undefined ? x : sum(x+y)
Kal hi inetrview ab pura din ye channel k videos dekhne hai ... Ek sath me 😜 , anyways you are doing good job. Thanks
for python developers this can be achieved like this:
class SUM:
val = 0
def __init__(self, val):
self.val += val
def __call__(self, val):
self.val += val
return self
def __str__(self):
return str(self.val)
print(SUM(1)(2)(3)(4)(5)(6)) #21
Thank you for a wonderful explanation😊 I am updating my js skills your videos are helping a lot😊✌👍
The way you explain is awesome
Very Awesome Explanation. Thank you
I think under the arrow function you don't need a return statement instead of that simply right; let sum = a => b => b ? sum(a+b) : a; console.log(sum(4)(5)(2)());
Hi Akshay you are explaining complex topics in a simple way ,thanks a lot for that :)
Thanks a lot Akshay, for all your efforts in making these videos it has helped me and many others to crack the interviews. I am really grateful to you. 🙏😊
That's great. Congratulations! 😇
@@akshaymarch7 Thanks a lot :)
Just awesome ! Keep going ...
beauty of recursion
Sir can you please create a detailed video with a lot of example of currying function, please? I know you have already a video on the topic and I watched that. But somehow I feel like you can make it awesome.
Wow, that was a 1 line code , Liked it :) (y).
This was the one which I arrived at :
function sum(currentTotal) {
if(!currentTotal) return 0;
return function(num) {
if(!num) return currentTotal;
return sum(currentTotal + num);
}
}
Plz made video on angular Interview questions for UI developer
To support variadric functions:
const add = (...a) => (...b) => b.length ? add(...a, ...b) : a.reduce((a, b) => a + b, 0);
add(1,2)(3,4)(5)(); // 15
Using an empty parameter invocation as a terminator seems a little bit janky in practical usage. It's probably great to override the returning functions valueOf() as a way to generate the value.
Although a bit lengthy:
const add = (...a) => {
const $add = (...b) => {
a = a.concat(b);
return $add;
}
$add.valueOf = () => a.reduce((x,y) => x + y, 0);
return $add;
}
+add(1)(2,3)(4,5); //15
Note the usage of the unary '+' operator as a means to get the primitive value of the function.
source: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/valueOf
Thanks a lot, Ryan. That's a great contribution, it deserves to be pinned on the top!
I am learning a lot about js now. Yups . Thanks Akshay for being my inspiration
Hello, I really liked the video, you explained in detail. Can you also explain how instead of sum which we do inside the function , how we can apply the function which was passed as an argument
nice description, thx.
but how about situations, when call simple sum(1,5) or call sum(1)(2) without () on the end? maybe change function, witch can pass thus case
great explanation ..thank you
very good job Akshay....please keep it continue ...it is very helpful.....
Can you please give an understanding for my question...
I was asked a this question when I was hunting job, that was balance the string with braces for an example "{a}[b]{c:[c]}" if a kind of braces start it should properly close.
Yeah, sure. This is also a very common question asked in the interviews. I've myself faced it. Give me some time I'll surely come up with that. 😊
And glad that you liked the video, your compliments make me work more hard and come up with something better everytime to help everyone. Thanks. 😊
@@akshaymarch7 You are doing a very good job ... and it will help for job seekers like me ;)
Really well explained!
Can u tell me the salary of a front end developer in a product base company like Microsoft ,Adobe ,LinkedIn
I was asked this same question in an interview with PwC.
Can u tell me the salary of a front end developer in a product base company like Microsoft ,Adobe ,LinkedIn
@@Anand-zg6jv15 to 20 LPA.
@Akshay Saini, you are doing awesome job. can you make video on how to use immutable.js to structure data in our applications.
I was asked this question when I was interviewing with one of the companies in Delhi.
Can u tell me the salary of a front end developer in a product base company like Microsoft ,Adobe ,LinkedIn
Thanks Akshay bro.. I didn't get in first time but got it in second time.
Nice explanation
awesome video and explaination
Akshay in this example it will return correct output for sum(1)(2)(3)(4)(). But how we will write the code for this sum(1)(2)(3)(4) and output should be 10. I tried and I am getting function as return value. Can we do that or not?
curry = (fn, length) => function curried(...args) { return length != args.length ? curried.bind(null, ...args) : fn.apply(null, args); };
add = (a,b)=>a+b;
finalAdd = curry(add, 2);
finalAdd(1)(2); //=> 3
Very helpful to learn
const sum = (a) => (b) => b ? sum(a+b) : a;
Thank you mate :)
👍
Sir, awesome please keep solving and put some questions. So anyone can tey to solve also.
Hi Akshay... I just got an offer as fresher from a company in Bangalore and they asked this question, I was not able to answer but I answered other questions, I explained concepts as you did, they were impressed. your videos helped me a lot to reach there. Thanks a lot. and I would like to dedicate my first salary to a few of my UA-cam gurus, and you also one among them. kindly let me know how can I support you.
you re genius.
I was asked this question in an interview today and my bad I wasn't able to crack it as I didn't come across this video before. Hope I'll crack it in future interviews.
Hi Akshay,
Thanks for making this video. I was wondering if you would classify this solution as an example of 'currying' ?
Hi Akshay I saw your all video are awesome. For js concept as well as interview both .
I am unlucky to miss this video, I have been asked in two interviews till now
Ha ha you are so poor bro.
Seriously man which company
@@rajeshp9319 Ameriprise
thanks. great solution and explanation.
Very helpful ❤️
Awesome questions! Keep up the good work whenever you get time :-)
So finally I am able to fix my keyboard now after watching this video :-)
The following question you'll be getting after this at Amazon is performance. Learn about Memoization as well.
@avtar nanrey. I have interview scheduled with Amazon. Can you please provide more tips?
We can also use an arrow function and take all the argument and pass it one by one, for ex: const fun = (a)=>(b)=> {
// Code here
}
Correct me if I'm wrong
Looks fine
Thaks for the video.
Can you make a video on, how this works in function() and arrow function
const sum = a => (b) => {
if (b) return sum(a + b);
return a;
};
console.log(sum(1)(2)());
Hi Akash,first of all i would like to thank for kind of knowledge you are sharing through your videos.i have faced question about web page optimization in many interview,can you make good video on that.it will be really good knowledge to share i think.
function sum(num, total = 0) {
if(num === undefined) {
return total
}
return (newNum) => sum(newNum, total + num)
}
This is what I implemented before checking the solution.
Hi Akshay.
Being a front end developer, I've faced similar questions while on job hunt.
Your videos are extremely informative and helpful and I am sure it'd definitely help job seekers out there.
Keep up the good work. I hope to see more contents.
I've a small request for you. A video on javascript design patterns and how different libraries use them under the hood might come in handy somedays.
Sure, Abhijeet. I've noted it down, will try to cover it. It will be a great value add. Thanks for your suggestion :)
Can u tell me the salary of a front end developer in a product base company like Microsoft ,Adobe ,LinkedIn
Love you bro, ❤️🙏🏻 faadu vid
Let sum = a=> b=> return b? Sum(a+b) : a will have an error. I believe we need to put the return statement in {} or else we can completely omit the return. It will still work.
Hi Akshay , This was good and detailed information on sum(1)(2)(3)() . I have few queries , suppose if the last() is not given and we are still asked to return sum , how can we achieve it ?
for that case also the same logic will be applied
if the last() is not given and we are still asked to return sum, assign the function output to a variable and console log it
const addAll = sum(2)(3)(4);
console.log(addAll());
I've made use of debounce here :)
const sum = (function(){
let total = 0;
let timer;
function display(total){
clearTimeout(timer);
timer = setTimeout(function(){
console.log(total);
}, 0);
}
return function(num){
total += num;
display(total);
return sum;
}
})();
@@aldesi this is not working
@@aldesi its the same buddy afterall u are invoking the function by not passing any arguments
Nice bro 👌👌👌👌👌
super machi..
Hey nice to see ur video buddy.. Good luck..
Thanks Sajid :)
const sum = (a) => (a ? (b) => (b ? sum(a + b) : a) : 0);
This also handles `sum()` case.
Thanks man, really helpful
good explanation bro (y)
hi akshay , i love watching your videos , they are really informative , i have a request , can you make a video on asynchronous js , and important features in CSS
Hi Akash, Wen through your videos. really helpful. You have stopped adding videos.Any reason?
your videos awesome.
Hi akshay i am sure u have faced many frontend interview, i just wanted to know have u ever been asked system design question specific to frontend if yes can you please make some video on that
let arr=[1,2,8,2,1,3,6,7];
let obj={};
for(let i of arr){
obj[i]=true;
}
console.log(obj);
let b=Object.keys(obj);
console.log(b);
the above code is to remove duplicate from array, i didn't understand the flow inside the for loop. pls can u explain.
here obj is working as a HashMap
support 1 1 2 2 3 3 are your elements
so obj is basically counting the occurrence of each element and then for the unique element you are just printing the keys of the hashMap i.e obj
after for loop you obj will be like
{
1:2,
2:2,
3:3
}
see above keys are 1,2,3 and following colon are their occurrences in array and its pretty clear that keys will always give unique elements
Hope you understood it
Subscribed....I'm your subscriber now
love you Akshay Saini,
Nice bro...
Hello Akshay! I wrote this solution.
let sum = num1 => num2 => num3 => num4 => console.log(num4 + num3 + num2 + num1)
Though your solution is much more efficient!
@akshay: there is a variant of this question in which we have to write a function which will give same output to these two invocations
1) sum(1)(2)(3)....()
2) sum(1,2,3....)
Can you make a video for how to approach this question?
Thanks in advance
function sum(...a) {
if (a.length === 1) {
a = a[0];
} else {
return a.reduce((acc, item) => acc + item, 0);
}
return (b) => {
if (b == undefined) return a;
return sum(a + b);
};
}
console.log(sum(1)(0)(2)(0)(3)()); // 6
console.log(sum(1, 2, 3, 4, 5, 6)); // 21
3:10 sum(1)(2)() = 3
var sum = function (a){
return function(b){
return a + b;
}
}
it will not return 3 but a error : VM473:6 Uncaught TypeError: sum(...)(...) is not a function
Good