Create Hello World Function Problem
#2667
Description
LeetCode Problem 2667.
Write a function createHelloWorld. It should return a new function that always returns "Hello World".
Example 1:
Input: args = []
Output: "Hello World"
Explanation:
const f = createHelloWorld();
f(); // "Hello World"
The function returned by createHelloWorld should always return "Hello World".
Example 2:
Input: args = [{},null,42]
Output: "Hello World"
Explanation:
const f = createHelloWorld();
f({}, null, 42); // "Hello World"
Any arguments could be passed to the function but it should still always return "Hello World".
Constraints:
0 <= args.length <= 10
Solution
Approach: Closure
createHelloWorld is a factory: it returns a new function, and that function never looks at its arguments. Because the inner function ignores whatever it receives (a rest parameter is not even needed in JavaScript), every call returns the same string, with or without arguments.
Complexity: Time O(1), space O(1).
var createHelloWorld = function () {
// Arguments are ignored on purpose.
return function () {
return 'Hello World';
};
};