-
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.
- Loading branch information
Showing
1 changed file
with
35 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,35 @@ | ||
# Pipe function in JavaScript | ||
|
||
```javascript | ||
const surprise = | ||
(...fns) => | ||
(input) => | ||
fns.reduce((acc, fn) => fn(acc), input); | ||
``` | ||
|
||
A pipe function allows you to chain multiple operations together by taking a series of functions as arguments and applying them in a specific order to the input. | ||
|
||
Instead of doing something like this. | ||
|
||
```javascript | ||
const toUpperCase = (str) => str.toUpperCase(); | ||
const removeSpaces = (str) => str.replace(/\s/g, ""); | ||
const addExclamation = (str) => str + "!"; | ||
|
||
toUpperCase(removeSpaces(addExclamation("Subscribe to Bytes"))); | ||
``` | ||
|
||
You can do something like this. | ||
|
||
```javascript | ||
const pipe = | ||
(...fns) => | ||
(input) => | ||
fns.reduce((acc, fn) => fn(acc), input); | ||
|
||
const formatString = pipe(toUpperCase, removeSpaces, addExclamation); | ||
|
||
formatString("Subscribe to Bytes"); // SUBSCRIBETOBYTES! | ||
``` | ||
|
||
[source](https://bytes.dev/archives/341) |