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
RustでAWS Lambda functionをいい感じに書く
taiki45
2
150
Deep Dive into React Stream/Serialize
mugi_uno
4
860
GNU Makeの使い方 / How to use GNU Make
kaityo256
PRO
13
4.3k
The Design of Everyday APIs - PyCon 2024
roguelynn
0
170
TypeScriptコードの漸進的改善 / Progressive Improvement of TypeScript Code
medley
1
430
Effectで作る堅牢でスケーラブルなAPIゲートウェイ / Robust and Scalable API Gateway Built on Effect
yasaichi
7
1.2k
スタックトレース始めてみた
kuro_kurorrr
4
1.1k
酒飲んでたらテックリードになった話
spbaya0141
0
210
Findy - エンジニア向け会社紹介 / Findy Letter for Engineers
findyinc
2
74k
TypeScriptとGraphQLで実現する 型安全なAPI実装 / TSKaigi 2024
hokaccha
5
2.7k
FoodGram
iseruuuuu
0
230
Exploring Type-Informed Lint Rules in Rust based TypeScript Linters
unvalley
3
630
Featured
See All Featured
Distributed Sagas: A Protocol for Coordinating Microservices
caitiem20
323
20k
Navigating Team Friction
lara
179
13k
How To Stay Up To Date on Web Technology
chriscoyier
782
250k
YesSQL, Process and Tooling at Scale
rocio
165
13k
Dealing with People You Can't Stand - Big Design 2015
cassininazir
358
22k
Optimising Largest Contentful Paint
csswizardry
13
2.4k
Intergalactic Javascript Robots from Outer Space
tanoku
266
26k
The Success of Rails: Ensuring Growth for the Next 100 Years
eileencodes
34
6.1k
Rebuilding a faster, lazier Slack
samanthasiow
74
8.3k
実際に使うSQLの書き方 徹底解説 / pgcon21j-tutorial
soudai
123
39k
Making Projects Easy
brettharned
109
5.5k
Put a Button on it: Removing Barriers to Going Fast.
kastner
58
3.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!