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
REACT SP - Ramda + React
Search
Ana Luiza Portello
July 13, 2018
Programming
0
200
REACT SP - Ramda + React
Ana Luiza Portello
July 13, 2018
Tweet
Share
More Decks by Ana Luiza Portello
See All by Ana Luiza Portello
FRONTIN | Elas Programam - Programação Funcional no Front-end
anabastos
0
64
Workshop JSFP - SEMCOMP 2021
anabastos
0
230
Clojure é um Java melhor que Java - Codecon 2021
anabastos
0
120
Clojure 101 - Criciuma Dev
anabastos
0
290
TDC POA - GraphQL
anabastos
1
240
TDC Porto Alegre 2019 - JS Funcional com Ramda
anabastos
0
210
BackEndSP - GraphQL
anabastos
0
200
Git & Github - RLadies
anabastos
1
210
Programaria Summit - Performance FrontEnd
anabastos
1
200
Other Decks in Programming
See All in Programming
Beyond ORM
77web
11
1.6k
AWS re:Invent 2024個人的まとめ
satoshi256kbyte
0
100
Jaspr Dart Web Framework 박제창 @Devfest 2024
itsmedreamwalker
0
150
Findy Team+ Awardを受賞したかった!ベストプラクティス応募内容をふりかえり、開発生産性向上もふりかえる / Findy Team Plus Award BestPractice and DPE Retrospective 2024
honyanya
0
140
月刊 競技プログラミングをお仕事に役立てるには
terryu16
1
1.2k
traP の部内 ISUCON とそれを支えるポータル / PISCON Portal
ikura_hamu
0
180
混沌とした例外処理とエラー監視に秩序をもたらす
morihirok
13
2.3k
DevinとCursorから学ぶAIエージェントメモリーの設計とMoatの考え方
itarutomy
0
150
盆栽転じて家具となる / Bonsai and Furnitures
aereal
0
1.9k
Lookerは可視化だけじゃない。UIコンポーネントもあるんだ!
ymd65536
1
130
React 19でお手軽にCSS-in-JSを自作する
yukukotani
5
560
Fixstars高速化コンテスト2024準優勝解法
eijirou
0
190
Featured
See All Featured
Visualizing Your Data: Incorporating Mongo into Loggly Infrastructure
mongodb
44
9.4k
ピンチをチャンスに:未来をつくるプロダクトロードマップ #pmconf2020
aki_iinuma
113
50k
Bash Introduction
62gerente
610
210k
Helping Users Find Their Own Way: Creating Modern Search Experiences
danielanewman
29
2.4k
Why Our Code Smells
bkeepers
PRO
335
57k
Six Lessons from altMBA
skipperchong
27
3.6k
Building an army of robots
kneath
302
45k
Visualization
eitanlees
146
15k
Code Review Best Practice
trishagee
65
17k
The Psychology of Web Performance [Beyond Tellerrand 2023]
tammyeverts
45
2.3k
4 Signs Your Business is Dying
shpigford
182
22k
Building Flexible Design Systems
yeseniaperezcruz
328
38k
Transcript
ANA LUIZA BASTOS github.com/anabastos @naluhh @anapbastos Software Developer na Quanto
e cientista da computação na PUC-SP anabastos.me
JSLADIES fb.com/jsladiesbr twitter.com/jsladiessp meetup.com/JsLadies-BR/ LAMBDA.IO t.me/lambdastudygroup github.com/lambda-study-group/ meetup.com/Lambda-I-O-Sampa- Meetup/
INTRODUÇAO AO RAMDA COM REACT
Biblioteca que foi pensada para tornar mais fácil o javascript
funcional
REACT + RAMDA
USOS CONVENIÊNTES / REFACTORZINHOS
PQ RAMDA?
• faz uso de conceitos funcionais • 100% imutável •
ganho em performance • elegante • point-free • etc
• Lists(map, filter, reduce, contains, replace, passAll, crop, flatten, find)
• Maths(inc, add, mean, sum) • String(split, replace) • Logics(equals, cond, not) • Relation(intersection, clamp, gt, lt) • Functions(curry, pipe, compose, ifElse, etc)
TODAS AS FUNÇÕES SÃO CURRIED
const add = (x, y) => x + y add(1,
2); // 3 add(1) // Error
(curry)
const curryAdd = R.curry((x, y) => x + y)) curryAdd(1,
2); // 3 const addOne = curryAdd(1); // Function addOne(2) // 3
STATELESS FUNCTIONS todo list
const Container = children => (<div>{children}</div>); const List = children
=> (<ul>{children}</ul>); const ListItem = ({ id, text }) => (<li key={id}> <span>{text}</span> </li>);
const TodoItem = { id: 123, text: 'Comprar pão' };
Container(List(ListItem(TodoItem))); Comprar pão
COMPOSE HIGH ORDER COMPONENTS (pipe / compose)
PIPE / COMPOSE: compõe funções de forma sequencial
function1 function2
Composed Function
PIPE COMPOSE
// Container(List(ListItem(TodoItem))); const TodoList = R.compose( Container, List, ListItem );
TodoList(TodoItem); Comprar pão
const TodoItems = [{...}, {...}, {...}] const TodoList = R.compose(
Container, List, R.map(ListItems) ); TodoList(TodoItems); Comprar pão Pagar boletos Ir pra react sp na neon
const TodoItems = [{...}, {...}, {...}] const TodoList = R.compose(
Container, List, R.map(ListItems), R.sort(byId), ); const byId = R.ascend(R.prop(‘id’)) TodoList(TodoItems);
const sortedListItems = R.pipe( R.sort(byId), R.map(ListItems), )
const TodoItems = [{...}, {...}, {...}] const TodoList = R.compose(
Container, List, sortedListItems, ); TodoList(TodoItems);
COMPOSIÇAO DE PROMISE (pipeP / composeP)
const todoList = R.pipeP( getUserById, getTodos, funçãoAsyncQueFazWhatever, ) // Promise
await todoList(‘123’)
DATA HANDLING (Evolve, ApplySpec)
EVOLVE
R.evolve({ email: R.toLower, phone: R.replace(‘-’, ‘’), name: R.trim, })(data)
// state { // …, // selected: false, // …
, // } onToggleSelected() { this.setState((prevState) => ({ ...prevState selected: !prevState.selected })) }
onToggleSelected() { this.setState(R.evolve({ selected: R.not })) }
APPLY SPEC
const createObj = R.applySpec({ counter: R.inc, userData: { phone: R.trim},
}) createObj(0, “ 98499-1900”) // {1, userData{ phone: “9849919000”}}
const handlePhone = R.pipe( R.split(‘-’), R.join, R.replace(/[^0-9]/, ‘’), algumaCoisa, //
(str) => {str} )
const createObj = R.applySpec({ counter: R.inc, userData: { phone: handlePhone},
})
IMMUTABLE STATE (lenses)
currentState -> newState 0 - +
const counterLens = R.lensProp('counter'); counterLens(state) //{ counter: 0 }
// state = { a: { b: { counter: 0
} const counterLens = R.lensPath(['a','b','counter']); counterLens(state)
// const state = {counter : 0} // view const
getCounter = R.view(counterLens) // 0 getCounter(state) // 0 // set const setCounter = R.set(counterLens, 1) setCounter(state) // 1 // over const incCounter = R.over(counterLens, R.inc) incCounter(state) // 1
// sem lens :( this.setState((prevState) => { ({ counter: prevState.a.b.counter++
})) } // com lens :) this.setState(incCounter)
render() { const count = getCounter(this.state) return (<div>{count}</div>) }
• Se foca em apenas uma propriedade do objeto •
Não muta a propriedade • Consigo lidar caso a propriedade é undefined • Torna bem mais declarativo
SWITCH CASE / IF (cond)
switch (action.type) { case 'INCREMENT': return state + action.payload; case
'DECREMENT': return state - action.payload; default: return state; }
const load = R.cond([ [R.equals('INCREMENT'), R.inc(state)], [R.equals('DECREMENT'), R.dec(state)], [R.T, R.always(state)],
]) load(action.type)
const Content = (props) => { if(props.loading) { return <Loading
/> } if(props.items.length == 0) { return <Missing /> } return <Section {...props} /> }
const Content = R.cond([ [R.prop('loading'), Loading], [R.isEmpty(props.items), Missing], [R.T, Section],
]) Content(props)
STATIC COMPONENT (always)
const Loading = () => (<div>Loading</div>) ReactDOM.render(<Loading />, rootEl)
const Loading = R.always(<div>Loading</div>) ReactDOM.render(<Loading />, rootEl)
STYLED COMPONENTS (path)
const Name = () => styled.Text` font-weight: bold, font-size: 18px,
color: ${props => props.theme.primaryColor} `
const Name = () => styled.Text` font-weight: bold, font-size: 18px,
color: ${R.path([‘theme’, ‘primaryColor’])} `
• memoize(Function) • merge(List, Obj) • tryCatch(Function) • anyPass /
AllPass(List) • flatter(List)
RAMDASCRIPT
Nem sempre você tem um trade-off em legibilidade.
5 + 10 // 15 R.add(5, 10) // 15 [5,
10].reduce((x, y) => {x + y}, 0) [5, 10].reduce(add, 0)
const obj = {x: 10} R.prop(‘x’)(obj) // 10 obj.x //
10 R.sortBy(R.prop(‘x’)) R.prop(‘x’)({}) // undefined
BOM TOOLBOX
COOKBOOK
• Rambda - github.com/selfrefactor/rambda • Ramda-fantasy - github.com/ramda/ramda-fantasy • Ramda
React Redux Patterns - tommmyy.github.io/ramda-react-redux-patterns/ • Thinking Ramda - randycoulman.com/blog/2016/05/24/thinking-in-ramda-getting -started • Ramda - Derek Stavis(Pagar.me talks) • Hey Underscore, You’re doing it wrong - Brian Lonsdorf.
t.me/lambdastudygroup github.com/lambda-study-group
OBRIGADA :) https://speakerdeck.com/anabastos anabastos.me