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
/**
* @return {Function} return a function that always returns "Hello World".
*/
var createHelloWorld = function() {
return function(...args) {
return "Hello World"
}
};
/**
* const f = createHelloWorld();
* f(); // "Hello World"
*/
This code defines a function createHelloWorld
that returns another function. The returned function, when called with any arguments, will always return the string "Hello World".
Explanation:
createHelloWorld = function() { ... }
: This defines the createHelloWorld
function.return function(...args) { ... }
: Inside createHelloWorld
, a new anonymous function is created and returned. The ...args
syntax uses the rest parameter to collect all arguments passed to this function into an array named args
. This allows the function to accept any number of arguments.return "Hello World"
: Regardless of the arguments received (if any), the returned function always returns the string "Hello World".Example Usage:
const f = createHelloWorld();
console.log(f()); // Output: "Hello World"
console.log(f({}, null, 42)); // Output: "Hello World"
The time complexity of the returned function is O(1), because it simply returns a string, regardless of the input. The createHelloWorld
function itself also has a time complexity of O(1), as it only defines and returns another function.
The space complexity of the returned function is O(1), as it uses a constant amount of space to store the string "Hello World". The createHelloWorld
function also has a space complexity of O(1), as it only defines another function, requiring a constant amount of space.
There are no specific edge cases to consider for this problem, as the function is designed to always return the same string regardless of the input. The ...args
syntax handles any number of arguments, including no arguments, so there are no potential errors related to argument handling.