Require Cache Singleton

Require Cache Singleton

Medium NodeJS Node Basics & Modules 30 views
Explanation Complexity

Problem Statement

Show that requiring the same module twice returns the same instance.

Input Format

No input.

Output Format

Print true/false.

Constraints

Simulate require cache using a map.

Input / Output Format

Input Format
No input.
Output Format
Print true/false.
Constraints
Simulate require cache using a map.

Examples

Input:
Output:
true

Example Solution (Public)

NodeJS
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);

Official Solution Code

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);
Please login to submit solutions.
Editor
Output

                                        
Please login to submit solutions.