Recursive Object Evaluation
ObjectsAlgorithms
Implement a function compute that processes an object containing functions and nested objects.
Function Signature:
const compute = (input, a, b, c) => { // Your implementation };
Examples
Example 1
Input
const input1 = {
A: (a, b, c) => a + b + c,
B: (a, b, c) => a + b - c,
C: (a, b, c) => a - b - c,
};
compute(input1, 1, 1, 1);Output
{ a: 3, b: 1, c: -1 }Explanation
All functions are evaluated with arguments (1, 1, 1). A = 1+1+1 = 3, B = 1+1-1 = 1, C = 1-1-1 = -1. Keys are transformed to lowercase.
Example 2
Input
const input2 = {
A: (a, b, c) => a + b + c,
B: (a, b, c) => a + b - c,
C: (a, b, c) => a - b - c,
D: {
E: (a, b, c) => a + b + c,
},
};
compute(input2, 1, 1, 1);Output
{ a: 3, b: 1, c: -1, d: { e: 3 } }Explanation
The function recursively processes nested objects. The nested object `D` is processed, and its function `E` is evaluated. All keys are transformed to lowercase.
Constraints
- The input object can have any level of nesting
- Functions will always receive exactly three arguments (a, b, c)
- Non-function values should be preserved as-is
- Keys should be transformed to lowercase
Notes
- Use recursion to handle nested objects
- Check if a value is a function using `typeof value === "function"`
- Create a new object rather than modifying the input object
Hints
Editorial: Recursive Object Evaluation
Solution
The function recursively traverses the input object. For each key-value pair:
- If the value is a function, call it with
(a, b, c)and store the result with a lowercased key - If the value is an object, recursively call
evaluateon it - Return a new object with transformed keys and evaluated values
const compute = (input, a, b, c) => { const evaluate = (obj) => { const result = {}; for (const key in obj) { const value = obj[key]; if (typeof value === "function") { result[key.toLowerCase()] = value(a, b, c); } else if (typeof value === "object") { result[key.toLowerCase()] = evaluate(value); } } return result; }; return evaluate(input); };
Explanation
The evaluate function uses recursion to handle nested objects. It checks each value's type:
- Functions are invoked with the provided arguments
(a, b, c) - Objects trigger a recursive call to process nested structures
- Keys are transformed to lowercase using
key.toLowerCase()
The closure allows the inner evaluate function to access a, b, and c from the outer scope.
Time Complexity
O(n) where n is the total number of keys (including nested keys) in the object
Space Complexity
O(n) for the result object, plus O(d) for the call stack where d is the maximum depth of nesting
</>JavaScript
Loading editor…
Test Result
Run your code, or Submit to test it