callBefore

Returns a new function that can be called only for specific number of times.

1. Code

const callBefore = <T, S extends any[]>(
  fn: (...args: S) => T,
  count: number
): ((...args: S) => T | undefined) => {
  let counter = 0;
  return (...args: S): T | undefined => {
    if (counter < count) {
      counter++;
      return fn(...args);
    }
    return undefined;
  };
};

export default callBefore;

2. Installation

npx @jrtilak/lazykit@latest add callBefore

3. Description

The callBefore function is used to create a new function that can be called only for a specific number of times. After the specified number of calls, the function will always return undefined without executing the original function.

This is useful in some scenarios like rate limiting or trial period where you want to allow a function to be called only for a specific number of times.

4. Props

Prop

Type

Default Value

function*Function---
count*number---

5. Examples

import callBefore from ".";

const fn = (x: number) => x + 1;

const callBeforeFn = callBefore(fn, 2);

const result1 = callBeforeFn(1);
// Expected Output: 2

const result2 = callBeforeFn(2);
// Expected Output: 3

const result3 = callBeforeFn(3);
// Expected Output: undefined : as the function `fn` has been called twice already.