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
音楽のための関数型プログラミング言語mimiumにおける多段階計算の活用
tomoyanonymous
1
340
1B+ /day規模のログを管理する技術
broadleaf
0
140
コーディングルールの鮮度を保ちたい for SRE NEXT 2026 / keep-fresh-go-internal-conventions-sre-next-2026
handlename
0
140
分散システム、なんですぐ死んでしまうん?耐障害性を高めたいあなたのためのレジリエンスパターン入門
mshibuya
7
6.4k
自作OSでスライド発表する
uyuki234
1
3.9k
関数型プログラミングのメリットって何だろう?
wanko_it
0
180
act2-costs.pdf
sumedhbala
0
120
The Past, Present, and Future of Enterprise Java
ivargrimstad
0
280
鹿野さんに聞く!『TypeScriptコードレシピ集』で磨く実践力
tonkotsuboy_com
4
1.1k
The Bowling Game- From Imperative to Functional Programming - Part 1
philipschwarz
PRO
0
330
SREの積み重ねがAI駆動開発のガードレールになった ― 7つの実践/SRE Guardrails The 7
tomoyakitaura
8
4.5k
광주소프트웨어마이스터고등학교 DevFest 특강 - 바이브 코딩 시대에서 주니어 개발자로 살아남는 방법
utilforever
1
140
Featured
See All Featured
The SEO Collaboration Effect
kristinabergwall1
1
510
Groundhog Day: Seeking Process in Gaming for Health
codingconduct
0
250
Beyond borders and beyond the search box: How to win the global "messy middle" with AI-driven SEO
davidcarrasco
3
180
Introduction to Domain-Driven Design and Collaborative software design
baasie
1
900
The browser strikes back
jonoalderson
0
1.4k
How Software Deployment tools have changed in the past 20 years
geshan
0
34k
Templates, Plugins, & Blocks: Oh My! Creating the theme that thinks of everything
marktimemedia
31
2.8k
Leadership Guide Workshop - DevTernity 2021
reverentgeek
1
320
I Don’t Have Time: Getting Over the Fear to Launch Your Podcast
jcasabona
34
2.8k
State of Search Keynote: SEO is Dead Long Live SEO
ryanjones
0
220
Digital Projects Gone Horribly Wrong (And the UX Pros Who Still Save the Day) - Dean Schuster
uxyall
1
2k
Joys of Absence: A Defence of Solitary Play
codingconduct
1
410
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