Skip to content

Instantly share code, notes, and snippets.

@simeg

simeg/fp_js_3.js Secret

Last active May 23, 2022 08:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save simeg/f97b84fd2c34075d8a2ffa58346a85bc to your computer and use it in GitHub Desktop.
Save simeg/f97b84fd2c34075d8a2ffa58346a85bc to your computer and use it in GitHub Desktop.
FP in JS 3
// 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