Implement a `createSingleton` function. No matter how many times it is called, it should always return the same instance object.
Problem Statement
Implement a `createSingleton` function. No matter how many times it is called, it should always return the same instance object.
Complexity
Time Complexity: -
Space Complexity: -
Hints
š” Hint 1:
A singleton ensures only one instance exists throughout the application.
š” Hint 2:
Use a closure to store the instance privately.
š” Hint 3:
let instance; return () => { if (!instance) instance = { id: Date.now() }; return instance; };
ā
Solution:
```javascript
function createSingleton() {
let instance;
return () => {
if (!instance) instance = { created: true };
return instance;
};
}
```