skip to Main Content

talking about javascript (or typescript), I’m trying to find a way to make sure that developers can’t call a method multiple times with the same argument.

For example:

const foo = (name: string) => {}


foo("ABC") // ok

foo ("123") // ok

foo ("ABC") // should show an error, as it was already called in the first interaction

Just to be clear, the error should be shown at "developing" (compilation?) time. I want developers to be aware of the mistake while coding, so the IDE should trigger the error.

How can I achieve it? Should I create a tslint error?
Please help

3

Answers


  1. I don’t think you can statically do that, but you can throw an error at runtime in development only:

    const usedNames = []
    
    const foo = (name: string) => {
      if (process.env.NODE_ENV === 'development') {
        if (usedNames.includes(name)) throw new Error(`Function already called with ${ name }.`)
    
        usedNames.push(name)
      }
    
      ...
    }
    

    The whole if (process.env.NODE_ENV === 'development') { ... } block won’t be present in non-development builds.

    Login or Signup to reply.
  2. Unfortunately, TypeScript or JavaScript doesn’t have this kind of feature built-in. As far as I know, there’s no mechanism within JavaScript or TypeScript that allows you to enforce a restriction at compile-time based on runtime values or usage. The languages simply aren’t designed to keep track of this kind of usage.

    Typically, a static type checker like TypeScript checks types based on static analysis, which doesn’t involve executing or tracing the code. As a result, TypeScript can’t provide checks that depend on the runtime behaviour of the code, like the order or frequency of function calls.

    For catching these types of logical issues early, unit tests are often a better approach. You could write a test that asserts foo throws an error when called with the same argument twice, and then run your tests often during development. Alternatively, you could look into using a linter or static analysis tool that supports custom rules, but I don’t think any existing tool can handle this specific case.

    If you want to enforce a rule like this, your best bet might be to provide documentation or comments explaining the requirement, and to rely on developers to manually adhere to the requirement.

    It’s also possible that your use case could be better served with a different pattern or structure. If you find yourself needing to prevent developers from calling a method multiple times with the same argument, it might be worth considering a design that doesn’t allow for that possibility in the first place

    Login or Signup to reply.
  3. To ensure that developers can’t call a method multiple times with the same argument, you can create a caching mechanism to keep track of the arguments that have already been passed to the function. One approach to achieve this in JavaScript is by using a closure to store the cache and check for duplicate arguments.

    const createUniqueFunction = () => {
      const cache = new Set();
    
      const foo = (name) => {
        if (cache.has(name)) {
          console.error(`Error: "${name}" has already been used as an argument.`);
          return;
        }
    
        // Do whatever you want to do with the argument here
        console.log(`Processing argument: "${name}"`);
    
        // Add the argument to the cache
        cache.add(name);
      };
    
      return foo;
    };
    
    // Usage example:
    const foo = createUniqueFunction();
    
    foo("ABC"); // ok
    foo("123"); // ok
    foo("ABC"); // Error: "ABC" has already been used as an argument.
    

    In this example, we use a closure to create the createUniqueFunction function, which returns the foo function. The cache variable inside the closure is a Set that stores the arguments passed to foo. Before processing the argument, we check if it already exists in the cache. If it does, we log an error message and return early without performing the operation.

    By using this approach, calling foo multiple times with the same argument will result in an error message, preventing duplicate calls with the same argument.

    Keep in mind that the above code will work as long as the foo function is created using createUniqueFunction. If you create another foo function separately, it will have its own independent cache. If you need to ensure uniqueness across multiple instances, you could explore other approaches like using a global cache or a custom data structure.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search