From c58488d1e71a279360d79c700e05ffbc0e8a31e4 Mon Sep 17 00:00:00 2001 From: atomiks Date: Tue, 2 Jan 2018 09:40:46 +1100 Subject: [PATCH] Add once snippet --- snippets/once.md | 27 +++++++++++++++++++++++++++ tag_database | 1 + 2 files changed, 28 insertions(+) create mode 100644 snippets/once.md diff --git a/snippets/once.md b/snippets/once.md new file mode 100644 index 000000000..a3b3e6adb --- /dev/null +++ b/snippets/once.md @@ -0,0 +1,27 @@ +### once + +Ensures a function is called only once. + +Utilizing a closure, use a variable flag 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/rest (`...`) operator. + +```js +const once = fn => { + let called = false; + return (...args) => { + if (!called) { + fn(...args); + called = true; + } + }; +}; +``` + +```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 708f71b32..19bf1cbab 100644 --- a/tag_database +++ b/tag_database @@ -95,6 +95,7 @@ negate:logic nthElement:array objectFromPairs:object objectToPairs:object +once:function onUserInputChange:browser orderBy:object palindrome:string