Require Cache Singleton
NodeJS
Medium
4 views
Problem Description
Show that requiring the same module twice returns the same instance.
Output Format
Print true/false.
Constraints
Simulate require cache using a map.
Official Solution
const cache = new Map();
function requireSim(id, factory) {
if (cache.has(id)) return cache.get(id);
const mod = factory();
cache.set(id, mod);
return mod;
}
const a = requireSim('meetcode', () => ({ hits: 0 }));
const b = requireSim('meetcode', () => ({ hits: 999 }));
console.log(a === b);
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!