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
RailsConf 2024: Riffing on Rails: sketch your way to better designed code
kaspth
1
210
WinActorの勉強を継続する方法
tamai_63
0
130
TSKaigi 2024 - 新サービス Progate Path の演習で TypeScript を採用して見えた教材観点からの利点と課題
makotoshimazu
1
220
一文字エイリアスのすすめ
fujimura
0
190
Three ways to use AI on Android: The Good, the Bad and the Ugly
marxallski
0
120
Exploring the Implementation of “t.Run”, “t.Parallel”, and “t.Cleanup”
akarin
1
160
Adding Security to Microcontroller Ruby
sylph01
1
160
Next.js App Router
quramy
14
2.3k
Criando a Woovi em uma semana
daniloab
0
120
TCAとKMPを用いた新規動画配信アプリ 「ABEMA Live」の設計
tomu28
2
140
Try creating your own orderedmap
kazamori
1
280
欠陥を早期に発見するための Software Engineer in Test とその重要性 / What is Software Engineer in Test and How they works
orgachem
PRO
17
2.3k
Featured
See All Featured
Documentation Writing (for coders)
carmenintech
60
4k
JavaScript: Past, Present, and Future - NDC Porto 2020
reverentgeek
41
4.5k
Large-scale JavaScript Application Architecture
addyosmani
504
110k
Typedesign – Prime Four
hannesfritz
36
2.1k
Responsive Adventures: Dirty Tricks From The Dark Corners of Front-End
smashingmag
245
20k
Web development in the modern age
philhawksworth
203
10k
Why You Should Never Use an ORM
jnunemaker
PRO
51
8.7k
Fireside Chat
paigeccino
22
2.7k
The Invisible Customer
myddelton
114
12k
Let's Do A Bunch of Simple Stuff to Make Websites Faster
chriscoyier
501
140k
Design by the Numbers
sachag
274
18k
Designing the Hi-DPI Web
ddemaree
276
33k
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!