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
Sponsored
·
SiteGround - Reliable hosting with speed, security, and support you can count on.
→
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
セキュリティの専門家じゃなくてもできる。「セキュリティ意識」をアップデートして サプライチェーン攻撃への耐性を高めよう。
tk3fftk
5
930
Performance Engineering for Everyone
elenatanasoiu
0
220
Spec Driven Development | AI Summit Lisbon
danielsogl
PRO
0
210
Creating Composable Callables in Contemporary C++
rollbear
0
170
肥大化するレガシーコードに立ち向かうためのインターフェース分離と依存の逆転 / JJUG CCC 2026 Spring
hirokunimaeta
0
620
Claspは野良GASの夢をみるか
takter00
0
210
Spring Security 実践 ─ GraphQL APIで実務に役立つ 認証・認可 を学ぶ
wagyu
0
260
Hunting Vulnerabilities in Symfony with LLMs
vinceamstoutz
0
560
LLM本来の能力を解き放つサンドボックス技術とAI民主化への適用
yukukotani
3
4.5k
A2UI という光を覗いてみる
satohjohn
1
150
Vite+ Unified Toolchain for the Web
naokihaba
0
340
Inside Stream API
skrb
1
770
Featured
See All Featured
Ethics towards AI in product and experience design
skipperchong
2
310
It's Worth the Effort
3n
188
29k
Information Architects: The Missing Link in Design Systems
soysaucechin
0
980
The Director’s Chair: Orchestrating AI for Truly Effective Learning
tmiket
1
200
Design of three-dimensional binary manipulators for pick-and-place task avoiding obstacles (IECON2024)
konakalab
0
470
Making Projects Easy
brettharned
120
6.7k
Ruling the World: When Life Gets Gamed
codingconduct
0
260
The Anti-SEO Checklist Checklist. Pubcon Cyber Week
ryanjones
0
170
Evolving SEO for Evolving Search Engines
ryanjones
0
220
WENDY [Excerpt]
tessaabrams
11
38k
Reflections from 52 weeks, 52 projects
jeffersonlam
356
21k
Navigating Team Friction
lara
192
16k
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