forked from Chalarangelo/30-seconds-of-code
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request Chalarangelo#455 from atomiks/once
[ADD `once.md`] once
- Loading branch information
Showing
2 changed files
with
19 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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 | ||
``` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters