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
Javascript Funcional - Front End Campinas
Search
Ana Luiza Portello
July 27, 2017
Programming
0
290
Javascript Funcional - Front End Campinas
Palestra feita no Castelo Creative Space
Ana Luiza Portello
July 27, 2017
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
42
Workshop JSFP - SEMCOMP 2021
anabastos
0
210
Clojure é um Java melhor que Java - Codecon 2021
anabastos
0
89
Clojure 101 - Criciuma Dev
anabastos
0
270
TDC POA - GraphQL
anabastos
1
230
TDC Porto Alegre 2019 - JS Funcional com Ramda
anabastos
0
180
BackEndSP - GraphQL
anabastos
0
180
Git & Github - RLadies
anabastos
1
180
Programaria Summit - Performance FrontEnd
anabastos
1
170
Other Decks in Programming
See All in Programming
Open standards for building event-driven applications in the cloud
meteatamel
0
230
Ruby on Fails - effective error handling with Rails conventions
talyssonoc
0
290
WinActorの勉強を継続する方法
tamai_63
0
130
TypeScriptから始める VR生活
tamagokakeg
2
110
2024 コーディング研修
ckazu
2
640
Jetpack Composeとデザインシステム
rmakiyama
0
230
ペパボOpenTelemetry革命
pyama86
2
900
RaaP
ksss
0
150
mb_trim関数を作りました
youkidearitai
PRO
1
190
Amazon Aurora Serverless v2が意外と高かった話と、AWS Database Migration Serviceの話
satoshi256kbyte
1
110
Implementing Design Systems in Swift
seyfoyun
2
530
Native Federation: The Future of Micro Frontends in Angular
manfredsteyer
PRO
0
170
Featured
See All Featured
The Cult of Friendly URLs
andyhume
74
5.7k
Fantastic passwords and where to find them - at NoRuKo
philnash
39
2.5k
Dealing with People You Can't Stand - Big Design 2015
cassininazir
358
22k
Principles of Awesome APIs and How to Build Them.
keavy
121
16k
Visualization
eitanlees
137
14k
Done Done
chrislema
178
15k
Debugging Ruby Performance
tmm1
70
11k
Fashionably flexible responsive web design (full day workshop)
malarkey
398
65k
Refactoring Trust on Your Teams (GOTO; Chicago 2020)
rmw
26
2.3k
Clear Off the Table
cherdarchuk
86
310k
Stop Working from a Prison Cell
hatefulcrawdad
266
19k
No one is an island. Learnings from fostering a developers community.
thoeni
16
2.1k
Transcript
Javascript Funcional Jargões e boas práticas
@anabastos ANA BASTOS anabastos.github.io FullStack na Horizon Four.
JSLADIES fb.com/jsladiesbr twitter.com/jsladiessp meetup.com/JsLadies-BR/
Coisas que eu estou assumindo Conhecimento básico de Js. Um
pouco de ES6
O que é funcional?
Javascript pode ser funcional?
Funções
f(x) = x * x X Y 1 1 2
4 3 9
1 2 2 4 3 6 4 8 Domínio Imagem
x y=f(x) É uma função
1 2 2 3 4 3 Domínio Imagem x y=f(x)
É uma função
1 2 2 4 3 6 4 8 Domínio Imagem
x y=f(x) NÃO é uma função
1 2 2 4 3 6 4 Domínio Imagem x
y=f(x) NÃO é uma função
Funções Puras
Funções Puras Sempre recebem algo. Sempre retornam algo. Nunca mutam
coisas fora do escopo da própria função. Para o mesmo input sempre retornam o mesmo output.
Funções nunca devem depender do contexto em que elas estão
const taxa = 10 function valorTotal(valor) { return valor +
taxa }
function valorTotal(valor) { return valor + taxa }
Funções nunca devem mutar coisas fora do contexto delas mesmas
let taxa = 10 // variáveis globais são do mal
function mudarTaxa() { return taxa * 0.1 }
function mudarTaxa(taxa) { return taxa * 0.1 } const newTaxa
= mudarTaxa(taxa)
Efeito Colateral
DateTime. Escrever no banco de dados. Mutar variáveis fora do
escopo de função.
Imutabilidade
const ao invés de var ou let
None
const person = { name: 'Ana', age: 21 } const
newPerson = person newPerson.age = 22 console.log(newPerson === person) // true console.log(person) // { name: 'John', age: 30 }
None
object.assign()
const obj = { valor: 1337 } obj.valor = 42
const newObj = object .assign({}, obj, { valor: 42 })
. . .
const fruits = [ 'Maça', 'Abacaxi' ] const newFruits =
[ ...fruits, 'Laranja' ]
Function Expression
function add (x) { return x + 1 }
const add = function (x) { return x + 1
}
const add = function (x) { return x + 1
} const doubleAndAdd = function (x) { return add(x) * 2 }
Funções de primeira classe (high order functions)
High Order Functions Podem recebem uma ou mais funções como
argumento. Podem retornar funções.
map / filter / reduce > for
for function add(arr) { let results = [] for(let i
= 0; i < arr.length; i++) { results.push(arr[i] + 1) } } <- Muta o array <- Muta o i
Todo for pode ser substituído por um map, filter ou
reduce.
map 1 2 3 2 3 4 add(x)
Map const add = x => x + 1 const
arr = [1, 2 ,3] const res = arr.map(add) //[2, 3, 4]
filter 1 2 3 isEven(x) 2
filter const isEven = x => x % 2 ==
0 ? true : false const arr = [1, 2 ,3] const res = arr.filter(isEven) // [2]
reduce 1 2 3 sum(x) 6
reduce 1 2 3 sum(x) 6 const sum = (sum,
value) => sum + value [1, 2, 3].reduce(sum)
reduce 1 2 3 sum(x) 7 const sum = (sum,
value) => sum + value [1, 2, 3].reduce(sum, 1)
reduce const matrix = [ [0, 1], [2, 3], [4,
5] ] const flatten = (arr, value) => arr.concat(value) const flattened = matrix .reduce(flatten, []) // [0, 1, 2, 3, 4, 5]
MAP FILTER REDUCE food = [ ] (food, fry) =>
[ , , ] (food, isVeggie) => [ ] (food, eat) =>
Não mutam o array retornam um novo [1, 2, 3].map(add)
// [2, 3, 4]
Declarativo
Não programação imperativa descrevemos COMO queremos algo enquanto na declarativa
é mais O QUE deve ser feito.
suponto que eu um pedaço de bolo da geladeira...
Colocar no prato Ir pra cozinha Abrir a geladeira Pegar
o bolo Cortar bolo
Eu quero um pedaço de bolo
supondo que eu quero a soma dos valores + taxa
de 10% que são maiores que 500.
let results = [] for (let i = 0; i
< arr.length; i++) { withTax = arr[i] * 0.1 if (withTax > 500) { results.push(arr[i]) } } let sum = 0 for (let i = 0; i < results.length; i++) { sum += results[i] return results }
arr .map(res => res * 0.1) .filter(res => res >
500) .reduce((acc, res) => acc + res, 0)
Curry / Partial Application
const add = x => y => x + y
const add10 = add(10) // função const add10(5) // 15
NÃO USE CLASS não use new não use this não
use getters and setters
Modularizar em pequenas funções o que precisa ser resolvido.
Js não garante imutabilidade. Não 100% é puro. PRÓS CONTRAS
Mais testabilidade. Reduz erros e bugs. Mais legível. Lida melhor com o estado da sua aplicação.
http://ramdajs.com/repl/ https://github.com/fantasyland/fantasy-land https://facebook.github.io/immutable-js/ https://github.com/jfmengels/eslint-plugin-fp
proposal pattern matching proposal pipeline operator
recursion currying aridade composition
Desafio! tinyurl.com/desafiofuncionalcastelo
Obrigada!