Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Features
Speaker Deck
PRO
Sign in
Sign up for free
Search
Search
Faça programação funcional com JavaScript codan...
Search
Rogério Chaves
May 04, 2016
Programming
510
4
Share
Embed
Copy iframe code
Copy JS code
Copy link
Start on current slide
Faça programação funcional com JavaScript codando menos
Rogério Chaves
May 04, 2016
More Decks by Rogério Chaves
See All by Rogério Chaves
O problema das Fake News
rogeriochaves
1
200
A Brief History of Frontend
rogeriochaves
1
65
Implementando PWA em qualquer projeto
rogeriochaves
2
220
Microfrontends
rogeriochaves
2
150
Introducción a Elm
rogeriochaves
0
80
Immutable App Architecture
rogeriochaves
0
230
Introduction to Elm
rogeriochaves
2
160
Single State Atom apps
rogeriochaves
1
190
Playing with RxJS
rogeriochaves
0
120
Other Decks in Programming
See All in Programming
1B+ /day規模のログを管理する技術
broadleaf
0
110
AI時代のUIはどこへ行く?その2!
yusukebe
22
7.5k
LLMによるContent Moderationの本番運用の裏側と品質担保への挑戦
suikabar
3
750
Even G2とAWSで推しのエージェントを召喚しよう!
har1101
1
120
セキュリティの専門家じゃなくてもできる。「セキュリティ意識」をアップデートして サプライチェーン攻撃への耐性を高めよう。
tk3fftk
5
930
さぁV100、メモリをお食べ・・・
nilpe
0
150
Oxcを導入して開発体験が向上した話
yug1224
4
340
Javaの型とAI時代に型が大事な理由 / java types and type in AI era
kishida
2
150
はてなアカウント基盤 State of the Union
cockscomb
0
700
TAKTでAI駆動開発の品質を設計する
j5ik2o
7
1.5k
RTSPクライアントを自作してみた話
simotin13
0
630
Make SRE Operations Easier with Azure SRE Agent
kkamegawa
0
7.9k
Featured
See All Featured
Noah Learner - AI + Me: how we built a GSC Bulk Export data pipeline
techseoconnect
PRO
0
200
DevOps and Value Stream Thinking: Enabling flow, efficiency and business value
helenjbeal
1
240
Highjacked: Video Game Concept Design
rkendrick25
PRO
1
400
Utilizing Notion as your number one productivity tool
mfonobong
4
330
Design and Strategy: How to Deal with People Who Don’t "Get" Design
morganepeng
133
19k
Principles of Awesome APIs and How to Build Them.
keavy
128
18k
The Invisible Side of Design
smashingmag
301
52k
CoffeeScript is Beautiful & I Never Want to Write Plain JavaScript Again
sstephenson
162
16k
Creating an realtime collaboration tool: Agile Flush - .NET Oxford
marcduiker
35
2.5k
The untapped power of vector embeddings
frankvandijk
2
1.8k
How To Speak Unicorn (iThemes Webinar)
marktimemedia
1
490
The Pragmatic Product Professional
lauravandoore
37
7.3k
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