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
370
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
68
Workshop JSFP - SEMCOMP 2021
anabastos
0
240
Clojure é um Java melhor que Java - Codecon 2021
anabastos
0
130
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
Djangoアプリケーション 運用のリアル 〜問題発生から可視化、最適化への道〜 #pyconshizu
kashewnuts
1
260
苦しいTiDBへの移行を乗り越えて快適な運用を目指す
leveragestech
0
1k
ファインディLT_ポケモン対戦の定量的分析
fufufukakaka
0
920
なぜイベント駆動が必要なのか - CQRS/ESで解く複雑系システムの課題 -
j5ik2o
14
4.6k
Jakarta EE meets AI
ivargrimstad
0
350
PHPのバージョンアップ時にも役立ったAST
matsuo_atsushi
0
230
kintone開発を効率化するためにチームで試した施策とその結果を大放出!
oguemon
0
150
sappoRo.R #12 初心者セッション
kosugitti
0
280
1年目の私に伝えたい!テストコードを怖がらなくなるためのヒント/Tips for not being afraid of test code
push_gawa
1
590
PEPCは何を変えようとしていたのか
ken7253
2
230
パスキーのすべて ── 導入・UX設計・実装の紹介 / 20250213 パスキー開発者の集い
kuralab
3
900
Ruby on cygwin 2025-02
fd0
0
180
Featured
See All Featured
RailsConf & Balkan Ruby 2019: The Past, Present, and Future of Rails at GitHub
eileencodes
133
33k
[RailsConf 2023] Rails as a piece of cake
palkan
53
5.3k
Art, The Web, and Tiny UX
lynnandtonic
298
20k
BBQ
matthewcrist
87
9.5k
Evolution of real-time – Irina Nazarova, EuRuKo, 2024
irinanazarova
6
570
jQuery: Nuts, Bolts and Bling
dougneiner
63
7.7k
Building an army of robots
kneath
303
45k
The Cult of Friendly URLs
andyhume
78
6.2k
Exploring the Power of Turbo Streams & Action Cable | RailsConf2023
kevinliebholz
30
4.6k
Improving Core Web Vitals using Speculation Rules API
sergeychernyshev
10
510
Raft: Consensus for Rubyists
vanstee
137
6.8k
Gamification - CAS2011
davidbonilla
80
5.2k
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!