Skip to content

Commit f0d8b94

Browse files
committed
functional programming, pure functions
1 parent adfd44a commit f0d8b94

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed

Assets/PureFunctions.png

608 KB
Loading

FunctionalProgramming.md

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
# Functional Programming
2+
3+
Functional programming (often abbreviated FP) is the process of building software by composing pure functions, avoiding shared state, mutable data, and side-effects. Functional programming is declarative rather than imperative, and application state flows through pure functions. Contrast with object oriented programming, where application state is usually shared with methods in objects.
4+
5+
<i>[Reference Article](https://medium.com/javascript-scene/master-the-javascript-interview-what-is-functional-programming-7f218c68b3a0)</i>
6+
7+
## Pure Functions
8+
9+
![Pure Functions](./Assets/PureFunctions.png)
10+
11+
If you want to break things down in functional programming it all comes down to this concept of pure functions. The idea is that there's a separation between data over a program and the behavior of a program. All objects created in functional programming are immutable, so after it has been created it cannot be changed.
12+
13+
Rules:
14+
15+
- The function has to always return the same output, given the same input
16+
- The function cannot modify anything outside of itself
17+
- No side effects
18+
19+
<i>Example:</i>
20+
21+
```javascript
22+
const array = [1,2,3] // in the outside world (don't modify)
23+
24+
function removeLastItem(arr) {
25+
const newArray = [].concat(arr); // make a copy of the input instead of directly modifying it
26+
newArray.pop()
27+
return newArray
28+
}
29+
30+
function multiplyByTwo(arr) {
31+
return arr.map(item => item * 2) // using .map() will return a new array
32+
}
33+
34+
const array2 = removeLastItem(array);
35+
const array3 = multiplyByTwo(array);
36+
37+
console.log(array, array2, array3) // ->  [1, 2, 3] , [1, 2] , [2, 4, 6]
38+
```
39+
40+
#### <i>Example:</i> Amazon shopping feature
41+
42+
```javascript
43+
44+
```

0 commit comments

Comments
 (0)