Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Speaker Deck
PRO
Sign in
Sign up for free
Faça programação funcional com JavaScript codando menos
Rogério Chaves
May 04, 2016
Programming
4
320
Faça programação funcional com JavaScript codando menos
Rogério Chaves
May 04, 2016
Tweet
Share
More Decks by Rogério Chaves
See All by Rogério Chaves
O problema das Fake News
rogeriochaves
1
140
A Brief History of Frontend
rogeriochaves
1
15
Implementando PWA em qualquer projeto
rogeriochaves
2
150
Microfrontends
rogeriochaves
2
120
Introducción a Elm
rogeriochaves
0
59
Immutable App Architecture
rogeriochaves
0
190
Introduction to Elm
rogeriochaves
2
120
Single State Atom apps
rogeriochaves
1
150
Playing with RxJS
rogeriochaves
0
83
Other Decks in Programming
See All in Programming
GoogleI/O2022 LT報告会資料
shinsukefujita1126
0
310
UI Testing of Jetpack Compose Apps, AppDevCon
alexzhukovich
0
140
A Philosophy of Software Design 後半
yosuke_furukawa
PRO
10
2.7k
エンジニアによる事業指標計測のススメ
doyaaaaaken
1
180
シェーダー氷山発掘記
logilabo
0
140
ES2022の新機能
smt7174
0
230
GDG Seoul IO Extended 2022 - Android Compose
taehwandev
0
300
Node.jsデザインパターンを読んで
mmmommm
0
2.5k
Improving Developer Experience Through Tools and Techniques 2022
krzysztofzablocki
0
490
Amazon ECSのネットワーク関連コストの話
msato
0
630
実践エクストリームプログラミング / Extreme Programming in Practice
enk
1
500
Chart実装が楽になりました。
keisukeyamagishi
0
110
Featured
See All Featured
Bootstrapping a Software Product
garrettdimon
296
110k
Refactoring Trust on Your Teams (GOTO; Chicago 2020)
rmw
19
1.4k
Building Flexible Design Systems
yeseniaperezcruz
310
34k
Documentation Writing (for coders)
carmenhchung
48
2.5k
Code Reviewing Like a Champion
maltzj
506
37k
Happy Clients
brianwarren
89
5.6k
GitHub's CSS Performance
jonrohan
1020
420k
Fireside Chat
paigeccino
11
1.3k
The Power of CSS Pseudo Elements
geoffreycrofte
46
3.9k
The Invisible Side of Design
smashingmag
290
48k
A Tale of Four Properties
chriscoyier
149
21k
Docker and Python
trallard
27
1.6k
Transcript
FAÇA PROGRAMAÇÃO FUNCIONAL COM JAVASCRIPT CODANDO MENOS o que não
fazer para alcançar um código mais simples e funcional
2 @_rchaves_
os exemplos serão mostrados em JS, mas eles podem ser
adaptados pra praticamente qualquer linguagem de programação que possa passar funções ou lambdas como argumentos 3
as primeiras duas regras são as mais importantes, as outras
são uma mera consequência dessas 4
Premissa: com menos features, nós podemos ter um código mais
funcional e (discutivelmente) mais simples 5
MUTABILIDADE É UMA FEATURE 6 x = x + 1
x - x = 1 0 = 1 n o n s e n s e !
NÃO USE MUTABILIDADE 7 Não use Use var const let
no-var + no-let* + no-mutation* *usando eslint-plugin-immutable ESLint
EXEMPLOS 8 let myValues = [ 1, 2, 3 ];
myValues.push(4); return myValues; const myValues = [ 1, 2, 3 ]; return [ ...myValues, 4];
9 let foo = { name: 'Foo' }; foo.age =
32; return foo; const foo = { name: 'Foo' }; return { ...foo, age: 32 }; EXEMPLOS
AVOID VOID 10 doThis(); doThat(); return foo; eslint-plugin-no-implicit-side-effects ESLint result
= myFn(); Não use Use
11 addItemsToCart(); savePurchase(); updateScreen(); const updatedCart = addItems(cart, items); const
purchase = savePurchase(updatedCart); return view(purchase); EXEMPLOS
EXEMPLOS 12 addItemsToCart(); savePurchase(); updateScreen(); return view(savePurchase(addItems(cart, items)));
EXEMPLOS 13 array.push(5); object.key = 'five'; myObj.setFoo('bar'); i++; post('http://url', {});
return [ ...array, 5 ]; return { ...object, key: 5 }; return new MyObj('bar'); return i + 1; return post('http://url', {});
CAN’T TOUCH THIS 14 this params () => {} .bind(this)
*no-this *usando eslint-plugin-immutable ESLint doesn’t create this! Não use Use
EXEMPLOS 15 function distance () { return Math.abs(this.x - this.y);
} const distance = (x, y) => Math.abs(x - y);
EXEMPLOS 16 const name = user.getFormattedName(); const name = getFormattedName(user);
NÃO USE FOR/EACH 17 for reduce map .forEach filter no-for-loops*
+ no-implicit-side-effects** *usando bahmutov/eslint-rules ESLint **usando eslint-plugin-no-implicit-side-effects Não use Use
EXEMPLOS 18 let uppercaseNames = []; for (let i =
0; i < names.length; i++) { let uppercaseName = toUpperCase(names[i]); uppercaseNames.push(uppercaseName); } return uppercaseNames; return names.map(toUppercase);
EXEMPLOS 19 let total = 0; items.forEach((item) => { total
+= item.price; }); return total; return items.reduce((total, item) => total + item.price , 0);
EXEMPLOS 20 let names = []; let result = [];
list.forEach((item) => { const uppercasedName = toUpperCase(item.name); if (names.indexOf(uppercasedName) < 0) { names.push(uppercasedName); result.push({ name: uppercasedName, count: 1 }); } else { result[names.indexOf(uppercasedName)].count++; } }); return result; // input: [{name: ‘foo'}, {name: 'foo'}, {name: 'foo'}, {name: 'bar'}, {name: 'bar'}, {name: 'baz'}] // output: [{name: 'FOO', count: 3}, {name: 'BAR', count: 2}, {name: 'BAZ', count: 1}]
EXEMPLOS 21 const mapToUpperCase = list => list.map(item => ({
...item, name: toUpperCase(item.name) })); const countRepeated = (list, value) => list.reduce((total, item) => item.name === value.name ? total + 1 : total, 0); const addRepeatCount = list => list.map(item => ({ ...item, count: countRepeated(list, item) })); const removeDuplicates = list => list.filter((item, index) => list.indexOf(list.find(x => x.name === item.name)) === index); return removeDuplicates(addRepeatCount(mapToUpperCase(list)));
NÃO USE IF SEM ELSE 22 just if if/else if/return
ternary none :( ESLint Não use Use
23 if (foo) { return 'bar'; } if (foo) {
return 'bar'; } return 'baz'; if (foo) { return 'bar'; } else { return 'baz'; } foo ? 'bar' : 'baz'; EXEMPLOS
NÃO USE CLASSES 24 class functions *no-class *usando eslint-plugin-no-class ESLint
Não use Use
25 class Person { getFormattedName (person) { return person.name.toUpperCase(); }
save (person) { return post('http://saveName', { name: person.name }); } } const getFormattedName = (person) => person.name.toUpperCase(); const save = (person) => post('http://saveName', { name: person.name }); EXEMPLOS
26 class ListComponent extends React.Component { render () { return
<ul>{ this.listItems() }</ul>; } listItems () { return this.props.items.map(item => <li>{ item.name }</li>); } } const listComponent = (props) => <ul>{ listItems(props.items) }</ul>; const listItems = (items) => items.map(item => <li>{ item.name }</li>); EXEMPLOS
OU VOCÊ PODE USAR ELM vamos remover todas essas features!
OBRIGADO! ALGUMA PERGUNTA? bit.ly/pf-codando-menos
NO OPTIONAL ARGS (BONUS) 29 optional args for changing behaviour
specialized functions none :( ESLint function composition currying default args for common scenarios Não use Use
30 const getPrices = (items, onlyOdds = true) => {
const prices = items.map(item => item.price); if (onlyOdds) { return prices.filter(price => price % 2 !== 0); } return items; }; const getPrices = items => items.map(item => item.price); const getOddPrices = items => getPrices(items).filter(price => price % 2 !== 0); EXEMPLOS
31 const increasePrices = (items, by = 5) => items.map(item
=> ({ ...item, price: item.price + by })); increasePrices(list1); increasePrices(list2); increasePrices(list3, 10); const increasePrices = amount => items => items.map(item => ({ ...item, price: item.price + amount })); const increasePricesBy5 = increasePrices(5); const increasePricesBy10 = increasePrices(10); increasePricesBy5(list1); increasePricesBy5(list2); increasePricesBy10(list3); EXEMPLOS