Lazy Evaluation
JavaScript
medium
20 mins
Design a lazy function that wraps an initial function and returns an object that allows chaining of additional function calls. These functions should not execute immediately. Instead, all operations should be queued and only run in sequence when .execute() is called.
Example Inputs & Outputs
// Example 1: const add = (a, b) => a + b; const multiply = (a, b) => a * b; const result = lazy({add}).add(2, 3).execute(); // → 5 // Example 2: const result2 = lazy({multiply}).multiply(2, 3).add(4, 5).execute(); // multiply(2, 3) = 6, add(4, 5) = 9 → returns [6, 9] // Example 3: const divide = (a, b) => a / b; const result3 = lazy({divide}).divide(10, 2).divide(6, 3).execute(); // → [5, 2]
Constraints & Edge Cases
- Must support dynamic method names corresponding to function names (e.g.,
.add,.multiply). - Should return an array of results if multiple functions are queued.
- If no function is queued,
.execute()should return an empty array. - All arguments must be passed at chaining time and retained until execution.
- Must handle functions with varying numbers of arguments.
Companies:
google
apple
paytm
Solve Similar questions 🔥
Want to upskill? Explore our courses!
Namaste DSA
Master DSA from scratch with numerous problems, and expert guidance.
Namaste React
Wanna dive deep into React and become Frontend Expert? Learn with me now!
Namaste Frontend System Design
The most comprehensive and detailed course for frontend system design.
Namaste Node.js
Wanna dive deep into Node.js? Enroll into `Namaste Node.js` now!
