Currying with placeholder support : Explained with detail.
Rounit Ranjan Sinha
Posted on March 23, 2023
Currying is one of the most important concepts and also most asked JavaScript/Frontend interview question.
In this article we will be solving one question which uses currying and some array methods.
So, here we have some requirements to solve this question:
1) We have to check arguments length
2) We have to replace the "_", placeholder.
So, we have to write code inside function curry(as shown in question above.)
So, as we know that currying is a concept in javascript in which a function returns another function expecting the next argument(s).
So, here in function "curry" we had passed "func" as an argument.
and acc to this question this argument "func" is the join function.
Now, there may be a condition in which there are arguments coming to the function more than the expected function's length.
So, we don't want extra args, here we have used the splice method.
which is splicing the args from 0th position to the length of func(i.e., join here)
=> args.splice(0, func.length)
Now we need to check if the placeholder(i.e., "_" in this case) is present or not
So, we have used the Array.some() method of javascript.
**Now, let's understand that how this .some() method works, so basically it works like the filter() method but returns something else, actually as in filter method of javascript, we write some logic and if that element is present in the array then we return that element., but here in this some() method, instead of returning that element we return true if logic fits, else we return false.
Now, there maybe the condition where there is no placeholder present and the length is also equal to the expected length.
So we use the apply() method of javascript, basically this apply method accepts arguments as an array.(here in the code keyword "this" represents the function "func" itself)
And now the worst can happen is there is the presence of the placeholders and now we need to replace them in order to obtain expected output.
So, we need to iterate over the args to check the presence of the placeholders.
Here's the complete code.
I hope it helps :)
Follow for more such contents
Posted on March 23, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 29, 2024