Add 6 new snippets

This commit is contained in:
Chalarangelo
2022-04-02 18:03:16 +03:00
parent 003b4b21d0
commit 849d691679
6 changed files with 125 additions and 0 deletions

21
snippets/callOrReturn.md Normal file
View File

@ -0,0 +1,21 @@
---
title: Call or return
tags: function
expertise: beginner
firstSeen: 2022-04-04T05:00:00-04:00
---
Calls the argument if it's a function, otherwise returns it.
- Use the `typeof` operator to check if the given argument is a function.
- If it is, use the spread operator (`...`) to call it with the rest of the given arguments. Otherwise, return it.
```js
const callOrReturn = (fn, ...args) =>
typeof fn === 'function' ? fn(...args) : fn;
```
```js
callOrReturn(x => x + 1, 1); // 2
callOrReturn(1, 1); // 1
```