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*
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 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...
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)());
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 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
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)());
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)());
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 😊
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) } }
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.
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 :)
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.
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. 🙏😊
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.
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)());
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?
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
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. 😊
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.
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
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
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.
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
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 RUclips gurus, and you also one among them. kindly let me know how can I support you.
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); } }
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; } })();
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 do this as well : const curry = (fn) => { let curriedFunc; let len = 0; return curriedFunc = (...args) => { if(args.length === len) return fn(...args); len = args.length; return curriedFunc.bind(null, ...args); } }; const total = (...args) => args.reduce((prev, curr) => prev + curr, 0); const sum = curry(total); console.log(sum(1)(2)(3)());
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
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
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.
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
Hi @akshay In nested objects how will i get the values which is not an object from it. example object is {a:{a:{a:{a:5}},b:5},c:"sateesh"};. can you do a small video on 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
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.
good job Akshay n thanks for sharing i have a question what if i have something like this console.log(Sum(2)(2)(5)) eliminate/remove the last empty(). Btw rrrow functions undoubtedly make it pretty simple to get the required result: const Sum = a => b => b ? Sum( a + b ) : a;
How would you go about solving this if you weren't given the last function call with an undefined param? so sum(a)(b)(c)....( n) instead of sum(a)(b)(c)....( n)()... I don't think it's possible with your current solution. Your last function invocation will always return a reference to a the last call that will never get executed.
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
Just look at the transformation of Akshay between this series and the namaste javascript series. How much he has changed 🔥.
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)
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 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...
Man you are really very honestly giving all the knowledge with all the innocence. Really appreciate your effort.
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)());
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 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
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 :)
I was confused with the function,but now am happy.
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)());
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 😊
best java script teacher
was asked this same question in recent interview, which ofcourse I nailed thanks to you Akshay
When I used to go for interview in 2012 to 2014 I always wonder why I never encountered such situation while coding for projects 😀
Thank you so much dude. Everything is clear to me. Your videos make my foundation in JS better.
I was not able to solve it in an interview and was not short listed for next round, thanks for explanation
thankyou so much Akshay Sir, Amazing Amazing explanation of recursion!!
Thank you for the clear explanation! It was so helpful to see different variations too!
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)
}
}
Simply awesome.... just love it as your explanation
Thank You Akshay! Your videos are very important and best for Frontend Engineering positions
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.
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)
The way you explain is awesome
Kal hi inetrview ab pura din ye channel k videos dekhne hai ... Ek sath me 😜 , anyways you are doing good job. Thanks
wow... you made my day... great explanation on recursive function. Thankyou
Just awesome ! Keep going ...
Very Awesome Explanation. Thank you
Thank you for a wonderful explanation😊 I am updating my js skills your videos are helping a lot😊✌👍
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);
}
}
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.
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 :)
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.
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)());
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
Nice explanation
Love you bro, ❤️🙏🏻 faadu vid
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
great explanation ..thank you
Thanks Akshay bro.. I didn't get in first time but got it in second time.
That's called "Currying" in JS.
Very helpful to learn
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 ;)
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
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
awesome video and explaination
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
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.
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
beauty of recursion
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)()))
😅😅😅😅😅😅
So finally I am able to fix my keyboard now after watching this video :-)
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
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
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 RUclips gurus, and you also one among them. kindly let me know how can I support you.
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);
}
}
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.
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
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.
Very helpful ❤️
Hi Akshay,
Thanks for making this video. I was wondering if you would classify this solution as an example of 'currying' ?
Awesome
Hi Akshay I saw your all video are awesome. For js concept as well as interview both .
Subscribed....I'm your subscriber now
We can do this as well :
const curry = (fn) => {
let curriedFunc;
let len = 0;
return curriedFunc = (...args) => {
if(args.length === len) return fn(...args);
len = args.length;
return curriedFunc.bind(null, ...args);
}
};
const total = (...args) => args.reduce((prev, curr) => prev + curr, 0);
const sum = curry(total);
console.log(sum(1)(2)(3)());
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
thanks. great solution and explanation.
const sum = (a) => (b) => b ? sum(a+b) : a;
Thank you mate :)
👍
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
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?
const sum = (a) => (a ? (b) => (b ? sum(a + b) : a) : 0);
This also handles `sum()` case.
Thanks man, really helpful
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.
Awesome questions! Keep up the good work whenever you get time :-)
Really well explained!
Can u tell me the salary of a front end developer in a product base company like Microsoft ,Adobe ,LinkedIn
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!
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
Hi @akshay In nested objects how will i get the values which is not an object from it.
example object is {a:{a:{a:{a:5}},b:5},c:"sateesh"};. can you do a small video on it.
Hey nice to see ur video buddy.. Good luck..
Thanks Sajid :)
love you Akshay Saini,
Plz made video on angular Interview questions for UI developer
your videos awesome.
super machi..
@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
Seems there is a syntax error in the last simplified solution... Return is not needed throws error
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.
good explanation bro (y)
good job Akshay n thanks for sharing
i have a question what if i have something like this console.log(Sum(2)(2)(5)) eliminate/remove the last empty().
Btw rrrow functions undoubtedly make it pretty simple to get the required result:
const Sum = a => b => b ? Sum( a + b ) : a;
Please check the video description, I've added a link for code which works without parenthesis also. Hope that helps :)
@@akshaymarch7 Hello, the link posted for without parenthesis does not work. Can you please update it? Thank you!
How would you go about solving this if you weren't given the last function call with an undefined param? so sum(a)(b)(c)....( n) instead of sum(a)(b)(c)....( n)()... I don't think it's possible with your current solution. Your last function invocation will always return a reference to a the last call that will never get executed.
Check out the code link in the description. I've already posted the solution for that as well. 😊
@@akshaymarch7 code in link is not working, can you please check. :)
Sir, awesome please keep solving and put some questions. So anyone can tey to solve also.
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)?
A nice, but at the same time hard to read line of code.
const sum = a => b => b ? sum(a + b) : a;
Good
Nice bro...
@Akshay Saini, you are doing awesome job. can you make video on how to use immutable.js to structure data in our applications.
Nice bro 👌👌👌👌👌