-
-
Save simeg/f97b84fd2c34075d8a2ffa58346a85bc to your computer and use it in GitHub Desktop.
FP in JS 3
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
// A list of fruit, and their price | |
const fruit = [ | |
{name: 'banana', price: 5}, | |
{name: 'apple', price: 3}, | |
{name: 'pear', price: 7} | |
]; | |
// Now we want to increase the price of all fruit | |
// Let's do this using a for loop | |
// NOTE: We're also mutating state here, | |
// which as you know can be dangerous | |
for (f of fruit) { | |
f.price = f.price + 5; | |
} | |
// Instead, let's use map() | |
const moreExpensiveFruit = fruit | |
.map(f => { | |
return { ...f, price: f.price + 5 } | |
}); | |
// Now we're using functional programming! | |
// 1. We're not mutating fruit, instead we're copying data with the spread operatator `...` | |
// 2. map() returns a new list, so the fruit list is still unchanged |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment