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;
}
};
}
```