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
Documentation testsの恩恵 / Documentation testing benefits
ssssota
1
560
仕様と実装で学ぶOpenTelemetry
drumato
2
910
酒飲んでたらテックリードになった話
spbaya0141
0
210
An adventure of Happy Eyeballs
coe401_
1
140
Sheets API使ってみた
toshi0383
2
180
TypeScriptのパフォーマンス改善
yajihum
14
5k
Introducing Kotlin Multiplatform in an existing mobile app - Workshop Edition | AndroidMakers Paris
prof18
0
180
WinActorの勉強を継続する方法
tamai_63
0
130
ServerAction で Progressive Enhancement はどこまで頑張れるか? / progressive-enhancement-with-server-action
takefumiyoshii
6
510
otelcol receiver 自作RTA / Pepabo Tech Conference #22 春のSREまつり
arthur1
0
810
slow types ってなんだろう?
karad
0
210
Escolhendo (ou não) o melhor ORM para o seu projeto
andreiacsilva
1
160
Featured
See All Featured
Become a Pro
speakerdeck
PRO
13
4.6k
RailsConf 2023
tenderlove
9
580
Making the Leap to Tech Lead
cromwellryan
125
8.6k
KATA
mclloyd
16
12k
Web development in the modern age
philhawksworth
203
10k
How to name files
jennybc
65
94k
What's new in Ruby 2.0
geeforr
338
31k
It's Worth the Effort
3n
180
27k
Visualizing Your Data: Incorporating Mongo into Loggly Infrastructure
mongodb
34
8.9k
[Rails World 2023 - Day 1 Closing Keynote] - The Magic of Rails
eileencodes
9
1.3k
The World Runs on Bad Software
bkeepers
PRO
61
6.7k
The Brand Is Dead. Long Live the Brand.
mthomps
49
30k
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!