Explorer
Node.js

Write a `lazy(fn)` function that defers computation until .value is accessed. The function should only be called once and the result cached.

Problem Statement

Write a `lazy(fn)` function that defers computation until .value is accessed. The function should only be called once and the result cached.

Complexity

Time Complexity: -

Space Complexity: -

Hints

šŸ’” Hint 1: Lazy evaluation delays computation until the result is needed. šŸ’” Hint 2: Use a getter or property access to trigger computation. šŸ’” Hint 3: Cache the result after first computation. āœ… Solution: ```javascript function lazy(fn) { let computed = false; let result; return { get value() { if (!computed) { result = fn(); computed = true; } return result; } }; } ```

Lazy Evaluation

Medium
Write a `lazy(fn)` function that defers computation until .value is accessed. The function should only be called once and the result cached.
Editor
Loading Editor...
Evaluate code
Output:Click "Run" above to execute and verify your code here.
{"value":42,"calls":1}