jsartisan / frontend-challenges

FrontendChallenges is a collection of frontend interview questions and answers. It is designed to help you prepare for frontend interviews. It's free and open source.
https://frontend-challenges.com
27 stars 4 forks source link

Throttle 1 #20

Closed jsartisan closed 7 months ago

jsartisan commented 7 months ago

Info

difficulty: hard
title: throttle
template: javascript
tags: utility, lodash, javascript

Question

Implement a simple throttle function in JavaScript. The function should accept another function as its argument and return a new function that limits the rate at which the original function can be invoked. This means that the original function will be called at most once within a specified time window, regardless of how many times the throttled function is invoked during that period.

Ensure that the throttled function does not call the original function more than once within the specified time interval.

For example:

function originalFunction() {
  console.log("Function invoked!");
}

const throttledFunction = throttle(originalFunction, 500);

// The original function should be invoked 
// at most once within every 500 milliseconds
throttledFunction(); // Output: "Function invoked!"
throttledFunction(); // No immediate output
throttledFunction(); // No immediate output

// Wait for 500 milliseconds
throttledFunction(); // Output: "Function invoked!"

Template

index.js

export function throttle(cb, delay = 250) {
  // your answer here
}

index.test.js

import { throttle } from './index';

function wait(time) {
  return new Promise((resolve) => setTimeout(resolve, time));
}

describe('throttle function', () => {
  it('should throttle function calls', async () => {

    const mockFunction = jest.fn();

    const throttledFunction = throttle(mockFunction, 500);

    throttledFunction();
    throttledFunction();
    throttledFunction();

    await wait(600);
    expect(mockFunction).toHaveBeenCalledTimes(1);
  });

  it('should pass arguments correctly', async () => {
    const mockFunction = jest.fn();

    const throttledFunction = throttle(mockFunction, 500);

    throttledFunction(1);
    throttledFunction(2);

    await wait(600);
    expect(mockFunction).toHaveBeenCalledWith(1);
  });
});
github-actions[bot] commented 7 months ago

22 - Pull Request updated.