Skip to content

Commit

Permalink
Merge pull request Chalarangelo#455 from atomiks/once
Browse files Browse the repository at this point in the history
[ADD `once.md`] once
  • Loading branch information
Chalarangelo authored Jan 2, 2018
2 parents e9950a3 + bc5bea6 commit 347cb35
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 0 deletions.
18 changes: 18 additions & 0 deletions snippets/once.md
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
```
1 change: 1 addition & 0 deletions tag_database
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,7 @@ negate:logic
nthElement:array
objectFromPairs:object
objectToPairs:object
once:function
onUserInputChange:browser
orderBy:object
palindrome:string
Expand Down

0 comments on commit 347cb35

Please sign in to comment.