diff --git a/snippets/once.md b/snippets/once.md new file mode 100644 index 000000000..18e5fc886 --- /dev/null +++ b/snippets/once.md @@ -0,0 +1,18 @@ +### once + +Ensures a function is called only once. + +Utilizing a closure, use a flag, `called`, and set it to `true` once the function is called for the first time, preventing it from being called again. +Allow the function to be supplied with an arbitrary number of arguments using the spread (`...`) operator. + +```js +const once = fn => (called => (...args) => !called ? (called = true, fn(...args)) : undefined)() +``` + +```js +const startApp = event => { + // initializes the app + console.log(event); // access to any arguments supplied +}; +document.addEventListener('click', once(startApp)); // only runs `startApp` once upon click +``` diff --git a/tag_database b/tag_database index 636ab2469..540368f1d 100644 --- a/tag_database +++ b/tag_database @@ -103,6 +103,7 @@ negate:logic nthElement:array objectFromPairs:object objectToPairs:object +once:function onUserInputChange:browser orderBy:object palindrome:string