
Sponsored
Sponsored
This approach leverages closures to keep track of whether the original function has been called. A closure allows the function to maintain state across calls, which in this case is whether the function should execute or return undefined.
Time Complexity: O(1) for each call, Space Complexity: O(1), as no additional data structures are used.
1function once(fn) {
2This JavaScript solution defines a function once that takes a function fn as an argument. It uses a flag called to check if the function has been executed before. The first call executes fn and stores the result. Subsequent calls return undefined.
In this approach, use an external flag variable to keep track of whether the function has already been executed. This approach is more language-specific where closure support is limited.
Time Complexity: O(1) per call, Space Complexity: O(1) for state flag.
1#include <iostream>
2#include <functional>
3
4class Once {
5public:
6 Once(std::function<int(int, int, int)> fn) : fn(fn), called(false) {}
7
8 int operator()(int a, int b, int c) {
9 if (!called) {
10 called = true;
11 result = fn(a, b, c);
12 return result;
13 }
14 return -1; // Undefined equivalent
15 }
16
17private:
18 std::function<int(int, int, int)> fn;
19 bool called;
20 int result;
21};
22
23int main() {
24 Once onceFn([](int a, int b, int c){ return a + b + c; });
25 std::cout << onceFn(1, 2, 3) << std::endl; // Outputs the result
26 std::cout << onceFn(2, 3, 4) << std::endl; // Outputs undefined equivalent
27 return 0;
28}
29This C++ solution uses a class to manage the function call state. The class Once stores a flag called to track whether the function has been executed, ensuring it runs only once and returns an undefined equivalent on further calls.