In response to the recently created 30 Days of JS challenge on LeetCode, I'll be putting out my own solutions to each problem and working through a solving strategy while I'm at it.
The first challenge posted was #2667 - a problem involving a simple function-inside-function trick. Let's take a look.
Process
A brief set of instructions are given.
Write a function
createHelloWorld
. It should return a new function that always returns"Hello World"
.
The thing I'm liking about this particular set of problems chosen for the challenge is that the majority of them have unit tests that have already been written, giving us a guideline to shoot for.
Here's the test created for this problem.
const f = createHelloWorld();
f(); // "Hello World"
So we'll obviously start by making the createHelloWorld function, and following that we'll put another function in it that will be the return value for the first.
function createHelloWorld() {
return function() { return "Hello World" }
}
Note that this is ES5 syntax, using arrow functions is another option and can be done more simply by far because the function we're returning happens to be an anonymous function - a fantastic example of where we can use an arrow to shorten the code.
const createHelloWorld = () => () => "Hello World";
Conclusion
In three lines or one, this is a simple problem with a simple solution. The most important takeaway from this problem is that we can return functions from inside of functions - a critical feature that we're going to be using a lot in the coming challenges.
If you found this helpful, be sure to leave a 💖 on the post and a ⭐ on the Github repo!
Follow for more LC content :)
Top comments (0)