
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.
1import java.util.concurrent.atomic.
This Java approach uses an AtomicBoolean to track if the function has been called. This provides a thread-safe way to implement the 'once' behavior for multi-threaded environments.
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 <stdbool.h>
2#include <stdlib.h>
3#include <stdio.h>
4
5typedef int (*Function)(int, int, int);
6
7typedef struct {
8 Function fn;
9 bool called;
10 int result;
11} Once;
12
13Once* once(Function fn) {
14 Once* o = (Once*)malloc(sizeof(Once));
15 o->fn = fn;
16 o->called = false;
17 o->result = 0;
18 return o;
19}
20
21int once_call(Once* o, int a, int b, int c) {
22 if (!o->called) {
23 o->called = true;
24 o->result = o->fn(a, b, c);
25 return o->result;
26 }
27 return -1; // Represent undefined
28}
29
30int sum(int a, int b, int c) {
31 return a + b + c;
32}
33
34int main() {
35 Once* onceFn = once(sum);
36 printf("%d\n", once_call(onceFn, 1, 2, 3)); // Output the sum
37 printf("%d\n", once_call(onceFn, 2, 3, 6)); // Output undefined equivalent
38 free(onceFn);
39 return 0;
40}
41This C solution demonstrates using a structure to maintain state. The Once struct includes a function pointer and a flag called which checks for the first invocation. once_call executes only on the first call, thereafter returns an undefined equivalent.