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
68
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
yield再入門 #phpcon
o0h
PRO
0
550
フィードバックで育てるAI開発
kotaminato
1
120
Terraform標準の組織で AWS CDKをどう使うか
mu7889yoon
0
290
はてなアカウント基盤 State of the Union
cockscomb
1
1.3k
任せる範囲はこう広がった / How the Scope of AI Delegation Has Expanded
nrslib
1
260
初めてのKubernetes 本番運用でハマった話
oku053
0
130
【やさしく解説 設計編・中級 #6】良いアーキテクチャとは ~ 一本の登り道の、行き先 ~
panda728
PRO
0
170
Laravel Boostに学ぶ、AIにPHPを書かせる技術 〜OSSの実装から蒸留するエージェント制御の王道〜
kentaroutakeda
3
460
Haskell/Servantを通してWebミドルウェアを捉え直す
pizzacat83
1
590
OSINT for SRE: 学術論文とポストモーテムから探る システム障害の共通パターン / SRE NEXT 2026
tomoyk
1
3.9k
ローカルLLMでどこまでコードが書けるか -縮小版 / How much code can be written on a local LLM Shortened
kishida
2
190
PHP初心者セッション2026 〜生成AIでは見えない裏側を知る:今だからLAMPを通して仕組みを学ぶ〜
kashioka
0
520
Featured
See All Featured
Amusing Abliteration
ianozsvald
1
230
Distributed Sagas: A Protocol for Coordinating Microservices
caitiem20
333
23k
Stop Working from a Prison Cell
hatefulcrawdad
274
21k
The Pragmatic Product Professional
lauravandoore
37
7.4k
CoffeeScript is Beautiful & I Never Want to Write Plain JavaScript Again
sstephenson
162
16k
Believing is Seeing
oripsolob
1
170
Making Projects Easy
brettharned
120
6.7k
Evolution of real-time – Irina Nazarova, EuRuKo, 2024
irinanazarova
9
1.4k
Agile that works and the tools we love
rasmusluckow
331
22k
SEOcharity - Dark patterns in SEO and UX: How to avoid them and build a more ethical web
sarafernandez
0
220
Leo the Paperboy
mayatellez
8
1.9k
SEO Brein meetup: CTRL+C is not how to scale international SEO
lindahogenes
1
2.8k
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