Pergunta de entrevista da empresa Fragma Data Systems

1. What will be the output of the following code? let i = 1; function incrementByValue(value) { i += value; return i; } function limit(fn, maxCalls) { let calls = 0; return function (...args) { if (calls < maxCalls) { calls += 1; return fn(...args); } return undefined; }; } const callbytimes = limit(incrementByValue, 2); console.log(callbytimes(2)); console.log(callbytimes(3)); console.log(callbytimes(4)); console.log(callbytimes(10));

Resposta da entrevista

Sigiloso

6 de nov. de 2024

Global Variable i : The variable i is initialized to 1. It is used to store the cumulative value that will be updated by the incrementByValue function. incrementByValue Function: This function takes a value argument, adds it to i, and returns the updated value of i. It directly modifies the global variable i. limit Higher-Order Function: The limit function takes two parameters: fn (a function to be limited), maxCalls (the maximum number of times the function fn can be invoked). The limit function returns a new function that wraps the original function fn and tracks how many times it has been called using the calls variable. Returned Function Behavior: The returned function from limit increments the calls count each time it's invoked. If the calls count is less than maxCalls, it calls the original fn (in this case, incrementByValue) with the provided arguments and returns its result. If the calls count exceeds maxCalls, it returns undefined without calling fn again. Calling callbytimes: The callbytimes function is the wrapped version of incrementByValue with a limit of 2 calls. The console.log statements show: The first call with argument 2 increments i to 3. The second call with argument 3 increments i to 6. The third and fourth calls are ignored after the limit of 2 calls is reached, so undefined is returned.