Skip to content
Advertisement

Prevent calling a function more than once if the parameters have been used before

I would like a way to limit the calling of a function to once per values of parameters.

For example

JavaScript

Any suggestions? I’ve looked into using memoization but not established a solution just yet.

This is not solved by the suggested Prevent a function from being called twice in a row since that only solves when the previous func call had them parameters.

Advertisement

Answer

Memoization uses a mapping of arguments to return values. Here, you just want a mapping of arguments to None, which can be handled with a simple set.

JavaScript

With some care, this can be generalized to handle functions with multiple arguments, as long as they are hashable.

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement