SlideShare ist ein Scribd-Unternehmen logo
1 von 44
Downloaden Sie, um offline zu lesen
Globalcode – Open4education
Ramda
Derek Stavis
Software Engineer
Globalcode – Open4education
Who?
Derek Stavis
github.com/derekstavis
Software Engineer
Ruby, JavaScript, Python, C
Node, React & Webpack Advocate
Globalcode – Open4education
Have you been using functional
helper libraries?
Globalcode – Open4education
Underscore?
🤔
Globalcode – Open4education
Lodash?
🤔
Globalcode – Open4education
Really?
🙄
Globalcode – Open4education
Those are really good libraries
Globalcode – Open4education
Weren't designed with a functional
mindset from day 0
Globalcode – Open4education
Ramda
A functional programming library
http://ramdajs.com
Globalcode – Open4education
Meet Ramda
Emphasizes a purer functional style
Immutability and side-effect free functions
Ramda functions are automatically curried
Argument ordering convenient to currying
Keep rightmost the data to be operated
Globalcode – Open4education
Small, single-responsibility and
reusable functions
Globalcode – Open4education
Ramda shines on currying
Globalcode – Open4education
Ramda shines on currying
var names = [
{ name: 'Pablo' },
{ name: 'Escobar' },
{ name: 'Gaviria' }
]
var getName = R.prop('name')
var pickNames = R.map(getName, names)
pickNames()
=> [ 'Pablo', 'Escobar', 'Gaviria' ]
Globalcode – Open4education
Ramda shines on currying
var names = [
{ name: 'Pablo' },
{ name: 'Escobar' },
{ name: 'Gaviria' }
]
var getName = R.prop('name')
var pickNames = R.map(getName)
pickNames(names)
=> [ 'Pablo', 'Escobar', 'Gaviria' ]
Globalcode – Open4education
Currying?
😨
Globalcode – Open4education
Currying was named after
Haskell Curry
One of the first to investigate such technique
Globalcode – Open4education
Turn a function that expects
multiple arguments into one that,
when supplied fewer arguments,
returns a new function that awaits
the remaining ones
Globalcode – Open4education
Ramda is about currying
const cookPasta = R.curry((water, heat, pasta) => { ... })
// Have everything needed
cookPasta (water, heat, pasta)
// Forgot to buy pasta
cookPasta (water, heat)(pasta)
// No gas and no pasta
cookPasta (water)(heat, pasta)
// Had to go twice to supermarket
cookPasta (water)(heat)(pasta)
Globalcode – Open4education
This is truly powerful
Globalcode – Open4education
Ramda is all curried
😎
Globalcode – Open4education
Point-free programming
🖖
Globalcode – Open4education
Ramda is all curried
R.add(2, 3) //=> 5
R.add(7)(10) //=> 17
R.contains(2, [1, 2, 3]) //=> true
R.contains(1)([1, 2, 3]) //=> true
R.replace(/foo/g, 'bar', 'foo foo') //=> 'bar bar'
R.replace(/foo/g, 'bar')('foo foo') //=> 'bar bar'
R.replace(/foo/g)('bar')('foo foo') //=> 'bar bar'
Globalcode – Open4education
Apply the parameters left-to-right
when you have them
👉
Globalcode – Open4education
But what if you'd like to apply the
leftmost or intermediate arguments
before the rightmost?
Globalcode – Open4education
Leave argument placeholders
✍
Globalcode – Open4education
Functional placeholder
R.minus(R.__, 5)(10) //=> 5
R.divide(R.__, 5)(10) //=> 17
R.contains(R.__, [1, 2, 3])(2) //=> true
R.contains(R.__, [1, 2, 3])(1) //=> true
R.contains(R.__, R.__)(1)([1, 2, 3]) //=> true
Globalcode – Open4education
Or do partial application
Globalcode – Open4education
Ramda does partial application
both left-to-right and right-to-left
Globalcode – Open4education
In fact, there's no currying as in
theoretical math, Ramda currying
is, in reality, partial application
Globalcode – Open4education
Partial application
const greet = (salutation, title, name) =>
`${salutation}, ${title} ${name}!`
const greetMrCrowley = R.partialRight(greet, ['Mr.', 'Crowley'])
greetMrCrowley('Hello') //=> 'Hello, Mr. Crowley!'
const greetMr = R.partial(greet, ['Hello', 'Mr.'])
const greetMs = R.partial(greet, ['Hello', 'Ms.'])
greetMr('Mendel') // => 'Hello, Mr. Mendel'
greetMs('Curie') // => 'Hello, Ms. Curie'
Globalcode – Open4education
Ramda also makes available some
cool and very useful functions
Globalcode – Open4education
Avoiding you to rewrite the same
stuff that you always have to
Globalcode – Open4education
Ramda functions are divided into
various categories
Globalcode – Open4education
Ramda functions categories
Function
Math
List
Logic
Object
Relation
Globalcode – Open4education
Function functions
// Always return the same thing, ignoring arguments
const name = R.always('Derek')
name('Willian') //=> Derek
// Functional if then else, a.k.a. Maybe Monad
const findName = R.ifElse(
R.has('name'),
R.prop('name'),
R.always('No name')
)
findName({ title: 'Mr.', name: 'Derek' }) //=> Derek
findName({ title: 'Mr.' }) //=> No name
// Pipe functions left-to-right. First function can have any arity
// Others must have arity of exactly one
const calculate = R.pipe(Math.pow, R.negate, R.inc);
calculate(3, 2); // -(3^2) + 1
Globalcode – Open4education
Math functions
// Addition
R.add(1, 2) //=> 3
// Subtraction
R.subtract(2, 1) //=> 1
// Sum all elements
R.sum([1, 1, 1]) //=> 3
// Increment
R.inc(41) //=> 42
// Decrement
R.dec(43) //=> 42
// Calculate the mean
R.mean([2, 7, 9]) //=> 6
Globalcode – Open4education
List functions
// Check if all elements match a predicate
R.all(R.gt(4), [1, 2, 3]) //=> true
// Check if a number is inside a list
R.contains(3, [1, 2, 3])
// Drop elements from start
R.drop(1, ['foo', 'bar', 'baz']) //=> ['bar', 'baz']
// Find elements using a predicate
const list = [{a: 1}, {a: 2}, {a: 3}]
R.find(R.propEq('a', 2))(list) //=> {a: 2}
R.find(R.propEq('a', 4))(list) //=> undefined
// Flatten a list of list into a single list
const list = [1, 2, [3, 4], 5, [6, [7, 8, [9, [10, 11], 12]]]]
R.flatten(list) //=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
Globalcode – Open4education
Logic functions
// Combine predicates into a single function
var gt10 = x => x > 10
var even = x => x % 2 === 0
var gt10even = R.both(gt10, even)
gt10even(100) //=> true
gt10even(101) //=> false
// Functional switch case (aka. pattern matching?)
var whatHappensAtTemperature = R.cond([
[R.equals(0), R.always('water freezes at 0°C')],
[R.equals(100), R.always('water boils at 100°C')],
[R.T, temp => 'nothing special happens at ' + temp + '°C']
])
whatHappensAtTemperature(0) //=> 'water freezes at 0°C'
whatHappensAtTemperature(50) //=> 'nothing special happens at 50°C'
whatHappensAtTemperature(100) //=> 'water boils at 100°C'
Globalcode – Open4education
Object functions
// Add a key and value to an already existing object
R.assoc('c', 3, {a: 1, b: 2}) //=> {a: 1, b: 2, c: 3}
// Remove a key from an already existing object
R.dissoc('b', {a: 1, b: 2, c: 3}) //=> {a: 1, c: 3}
// Do the same with a nested path
R.assocPath(['a', 'b', 'c'], 42, {a: {b: {c: 0}}})
//=> {a: {b: {c: 42}}}
// Check if an object contains a key
var hasName = R.has('name')
hasName({name: 'alice'}) //=> true
hasName({name: 'bob'}) //=> true
hasName({}) //=> false
// Pick some properties from objects
var abby = {name: 'Abby', age: 7, hair: 'blond', grade: 2}
var fred = {name: 'Fred', age: 12, hair: 'brown', grade: 7}
R.project(['name', 'grade'], [abby, fred])
//=> [{name: 'Abby', grade: 2}, {name: 'Fred', grade: 7}]
Globalcode – Open4education
Relation functions
// Lots of comparison functions
// Kinda tricky, but also kinda natural
R.gt(2, 1) // 2 > 1
R.gt(2, 2) // 2 > 2
R.gte(2, 2) // 2 >= 2
R.gte(3, 2) // 3 >= 2
R.lt(2, 1) // 2 < 1
R.lt(2, 2) // 2 < 2
R.lte(2, 2) // 2 <= 2
R.lte(3, 2) // 3 <= 2
// Restrict a number to a range
R.clamp(1, 10, -1) // => 1
R.clamp(1, 10, 11) // => 10
// Intersect two lists
R.intersection([1,2,3,4], [7,6,4,3]) //=> [4, 3]
Globalcode – Open4education
Ramda works well with Promise
Globalcode – Open4education
Ramda and Promises
app.get('/v1/plants/:id', auth.active, (req, res) => {
db.plants.find({ id: req.params.id })
.then(R.head)
.then(R.bind(res.send, res))
})
Globalcode – Open4education
Ramda and Promises
function timesValues (number) {
return spot(number)
.then(spot =>
db.collection('zone_type_values')
.findOne({ id: spot.zone_type_value_id })
.then(R.prop('time_values'))
.then(R.assoc('timesValues', R.__, spot))
.then(R.pickAll(['id', 'name', 'timesValues']))
)
}
Globalcode – Open4education
Thanks for watching
Questions?
github.com/derekstavis
twitter.com/derekstavis
facebook.com/derekstavis

Weitere ähnliche Inhalte

Was ist angesagt?

Old Oracle Versions
Old Oracle VersionsOld Oracle Versions
Old Oracle Versions
Jeffrey Kemp
 

Was ist angesagt? (20)

Introduction to source{d} Engine and source{d} Lookout
Introduction to source{d} Engine and source{d} Lookout Introduction to source{d} Engine and source{d} Lookout
Introduction to source{d} Engine and source{d} Lookout
 
Java Full Throttle
Java Full ThrottleJava Full Throttle
Java Full Throttle
 
The Sincerest Form of Flattery
The Sincerest Form of FlatteryThe Sincerest Form of Flattery
The Sincerest Form of Flattery
 
Java 8 - project lambda
Java 8 - project lambdaJava 8 - project lambda
Java 8 - project lambda
 
Java Keeps Throttling Up!
Java Keeps Throttling Up!Java Keeps Throttling Up!
Java Keeps Throttling Up!
 
Java 8: the good parts!
Java 8: the good parts!Java 8: the good parts!
Java 8: the good parts!
 
Java Boilerplate Busters
Java Boilerplate BustersJava Boilerplate Busters
Java Boilerplate Busters
 
Intro to Functional Programming
Intro to Functional ProgrammingIntro to Functional Programming
Intro to Functional Programming
 
Thumbtack Expertise Days # 5 - Javaz
Thumbtack Expertise Days # 5 - JavazThumbtack Expertise Days # 5 - Javaz
Thumbtack Expertise Days # 5 - Javaz
 
Old Oracle Versions
Old Oracle VersionsOld Oracle Versions
Old Oracle Versions
 
Building Maintainable Applications in Apex
Building Maintainable Applications in ApexBuilding Maintainable Applications in Apex
Building Maintainable Applications in Apex
 
Go Go Gadget! - An Intro to Return Oriented Programming (ROP)
Go Go Gadget! - An Intro to Return Oriented Programming (ROP)Go Go Gadget! - An Intro to Return Oriented Programming (ROP)
Go Go Gadget! - An Intro to Return Oriented Programming (ROP)
 
Functional Programming In Java
Functional Programming In JavaFunctional Programming In Java
Functional Programming In Java
 
Creating Lazy stream in CSharp
Creating Lazy stream in CSharpCreating Lazy stream in CSharp
Creating Lazy stream in CSharp
 
Java 8, Streams & Collectors, patterns, performances and parallelization
Java 8, Streams & Collectors, patterns, performances and parallelizationJava 8, Streams & Collectors, patterns, performances and parallelization
Java 8, Streams & Collectors, patterns, performances and parallelization
 
Tork03 LT
Tork03 LT Tork03 LT
Tork03 LT
 
Functional programming in java
Functional programming in javaFunctional programming in java
Functional programming in java
 
Return Oriented Programming (ROP chaining)
Return Oriented Programming (ROP chaining)Return Oriented Programming (ROP chaining)
Return Oriented Programming (ROP chaining)
 
Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.
 
Regexes in .NET
Regexes in .NETRegexes in .NET
Regexes in .NET
 

Andere mochten auch

Andere mochten auch (20)

TDC2016POA | Trilha Empreendedorismo - Mulheres Empreendedoras: Porque a Igua...
TDC2016POA | Trilha Empreendedorismo - Mulheres Empreendedoras: Porque a Igua...TDC2016POA | Trilha Empreendedorismo - Mulheres Empreendedoras: Porque a Igua...
TDC2016POA | Trilha Empreendedorismo - Mulheres Empreendedoras: Porque a Igua...
 
Leilão do dia 2 de dezembro
Leilão do dia 2 de dezembroLeilão do dia 2 de dezembro
Leilão do dia 2 de dezembro
 
Mulheres Empreendedoras
Mulheres EmpreendedorasMulheres Empreendedoras
Mulheres Empreendedoras
 
Mulher empreendedora e-book
Mulher empreendedora e-bookMulher empreendedora e-book
Mulher empreendedora e-book
 
Como tirar a sua ideia do papel e transformar em um modelo de negócio inovador
Como tirar a sua ideia do papel e transformar em um modelo de negócio inovadorComo tirar a sua ideia do papel e transformar em um modelo de negócio inovador
Como tirar a sua ideia do papel e transformar em um modelo de negócio inovador
 
Rede Mulher Empreendedora
Rede Mulher Empreendedora Rede Mulher Empreendedora
Rede Mulher Empreendedora
 
O perfil da mulher de sucesso
O perfil da mulher de sucessoO perfil da mulher de sucesso
O perfil da mulher de sucesso
 
Análise do perfil da Mulher Empreendedora
Análise do perfil da Mulher EmpreendedoraAnálise do perfil da Mulher Empreendedora
Análise do perfil da Mulher Empreendedora
 
TDC2016POA | Trilha DevOps - DevOps Anti-Patterns
TDC2016POA | Trilha DevOps - DevOps Anti-PatternsTDC2016POA | Trilha DevOps - DevOps Anti-Patterns
TDC2016POA | Trilha DevOps - DevOps Anti-Patterns
 
TDC2016POA | Trilha DevOps - Monitoramento da infraestrutura para aplicac?o?e...
TDC2016POA | Trilha DevOps - Monitoramento da infraestrutura para aplicac?o?e...TDC2016POA | Trilha DevOps - Monitoramento da infraestrutura para aplicac?o?e...
TDC2016POA | Trilha DevOps - Monitoramento da infraestrutura para aplicac?o?e...
 
TDC2016POA | Trilha DevOps - Métricas, métricas para todos os lados!
TDC2016POA | Trilha DevOps - Métricas, métricas para todos os lados!TDC2016POA | Trilha DevOps - Métricas, métricas para todos os lados!
TDC2016POA | Trilha DevOps - Métricas, métricas para todos os lados!
 
TDC2016POA | Trilha DevOps - Monitoramento real-time com ELK
TDC2016POA | Trilha DevOps - Monitoramento real-time com ELKTDC2016POA | Trilha DevOps - Monitoramento real-time com ELK
TDC2016POA | Trilha DevOps - Monitoramento real-time com ELK
 
TDC2016POA | Trilha Arquetetura - Revitalizando aplicações desktop usando Ce...
TDC2016POA | Trilha Arquetetura -  Revitalizando aplicações desktop usando Ce...TDC2016POA | Trilha Arquetetura -  Revitalizando aplicações desktop usando Ce...
TDC2016POA | Trilha Arquetetura - Revitalizando aplicações desktop usando Ce...
 
TDC2016POA | Trilha Dinamica - Facilitação - Que momento o grupo se encontra?
TDC2016POA | Trilha Dinamica - Facilitação - Que momento o grupo se encontra?	TDC2016POA | Trilha Dinamica - Facilitação - Que momento o grupo se encontra?
TDC2016POA | Trilha Dinamica - Facilitação - Que momento o grupo se encontra?
 
TDC2016POA | Trilha Android - Firebase Cloud Messaging para Android e IoT
TDC2016POA | Trilha Android - Firebase Cloud Messaging para Android e IoTTDC2016POA | Trilha Android - Firebase Cloud Messaging para Android e IoT
TDC2016POA | Trilha Android - Firebase Cloud Messaging para Android e IoT
 
TDC2016POA | Trilha Arduino - A Prática do Arduino em Ensino: o Case de um La...
TDC2016POA | Trilha Arduino - A Prática do Arduino em Ensino: o Case de um La...TDC2016POA | Trilha Arduino - A Prática do Arduino em Ensino: o Case de um La...
TDC2016POA | Trilha Arduino - A Prática do Arduino em Ensino: o Case de um La...
 
TDC2016POA | Trilha Android - Monetização: conheça a rede de anúncios que pag...
TDC2016POA | Trilha Android - Monetização: conheça a rede de anúncios que pag...TDC2016POA | Trilha Android - Monetização: conheça a rede de anúncios que pag...
TDC2016POA | Trilha Android - Monetização: conheça a rede de anúncios que pag...
 
TDC2016POA | Trilha Dinamicas - Valores individuais e de sua equipe?
TDC2016POA | Trilha Dinamicas - Valores individuais e de sua equipe?TDC2016POA | Trilha Dinamicas - Valores individuais e de sua equipe?
TDC2016POA | Trilha Dinamicas - Valores individuais e de sua equipe?
 
TDC2016POA | Trilha Dinamica - Desenvolvimento de Ideias através de Brainwriting
TDC2016POA | Trilha Dinamica - Desenvolvimento de Ideias através de BrainwritingTDC2016POA | Trilha Dinamica - Desenvolvimento de Ideias através de Brainwriting
TDC2016POA | Trilha Dinamica - Desenvolvimento de Ideias através de Brainwriting
 
TDC2016POA | Trilha DevOps - Gestão de ciclo de vida de banco de dados: Já pa...
TDC2016POA | Trilha DevOps - Gestão de ciclo de vida de banco de dados: Já pa...TDC2016POA | Trilha DevOps - Gestão de ciclo de vida de banco de dados: Já pa...
TDC2016POA | Trilha DevOps - Gestão de ciclo de vida de banco de dados: Já pa...
 

Ähnlich wie TDC2016POA | Trilha Programacao Funcional - Ramda JS como alternativa a underscore e lodash

r,rstats,r language,r packages
r,rstats,r language,r packagesr,rstats,r language,r packages
r,rstats,r language,r packages
Ajay Ohri
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
David Padbury
 
Introducing PHP Latest Updates
Introducing PHP Latest UpdatesIntroducing PHP Latest Updates
Introducing PHP Latest Updates
Iftekhar Eather
 
Metaprogramovanie #1
Metaprogramovanie #1Metaprogramovanie #1
Metaprogramovanie #1
Jano Suchal
 
"Немного о функциональном программирование в JavaScript" Алексей Коваленко
"Немного о функциональном программирование в JavaScript" Алексей Коваленко"Немного о функциональном программирование в JavaScript" Алексей Коваленко
"Немного о функциональном программирование в JavaScript" Алексей Коваленко
Fwdays
 

Ähnlich wie TDC2016POA | Trilha Programacao Funcional - Ramda JS como alternativa a underscore e lodash (20)

2007 09 10 Fzi Training Groovy Grails V Ws
2007 09 10 Fzi Training Groovy Grails V Ws2007 09 10 Fzi Training Groovy Grails V Ws
2007 09 10 Fzi Training Groovy Grails V Ws
 
Easy R
Easy REasy R
Easy R
 
r,rstats,r language,r packages
r,rstats,r language,r packagesr,rstats,r language,r packages
r,rstats,r language,r packages
 
Groovy
GroovyGroovy
Groovy
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
 
A limited guide to intermediate and advanced Ruby
A limited guide to intermediate and advanced RubyA limited guide to intermediate and advanced Ruby
A limited guide to intermediate and advanced Ruby
 
GPars For Beginners
GPars For BeginnersGPars For Beginners
GPars For Beginners
 
Mongoskin - Guilin
Mongoskin - GuilinMongoskin - Guilin
Mongoskin - Guilin
 
Introducing PHP Latest Updates
Introducing PHP Latest UpdatesIntroducing PHP Latest Updates
Introducing PHP Latest Updates
 
Metaprogramovanie #1
Metaprogramovanie #1Metaprogramovanie #1
Metaprogramovanie #1
 
"Немного о функциональном программирование в JavaScript" Алексей Коваленко
"Немного о функциональном программирование в JavaScript" Алексей Коваленко"Немного о функциональном программирование в JavaScript" Алексей Коваленко
"Немного о функциональном программирование в JavaScript" Алексей Коваленко
 
Ruby from zero to hero
Ruby from zero to heroRuby from zero to hero
Ruby from zero to hero
 
Functional programming in javascript
Functional programming in javascriptFunctional programming in javascript
Functional programming in javascript
 
Functional techniques in Ruby
Functional techniques in RubyFunctional techniques in Ruby
Functional techniques in Ruby
 
Functional techniques in Ruby
Functional techniques in RubyFunctional techniques in Ruby
Functional techniques in Ruby
 
Php Tutorials for Beginners
Php Tutorials for BeginnersPhp Tutorials for Beginners
Php Tutorials for Beginners
 
php AND MYSQL _ppt.pdf
php AND MYSQL _ppt.pdfphp AND MYSQL _ppt.pdf
php AND MYSQL _ppt.pdf
 
Php my sql - functions - arrays - tutorial - programmerblog.net
Php my sql - functions - arrays - tutorial - programmerblog.netPhp my sql - functions - arrays - tutorial - programmerblog.net
Php my sql - functions - arrays - tutorial - programmerblog.net
 
Tackling repetitive tasks with serial or parallel programming in R
Tackling repetitive tasks with serial or parallel programming in RTackling repetitive tasks with serial or parallel programming in R
Tackling repetitive tasks with serial or parallel programming in R
 
Why react matters
Why react mattersWhy react matters
Why react matters
 

Mehr von tdc-globalcode

Mehr von tdc-globalcode (20)

TDC2019 Intel Software Day - Visao Computacional e IA a servico da humanidade
TDC2019 Intel Software Day - Visao Computacional e IA a servico da humanidadeTDC2019 Intel Software Day - Visao Computacional e IA a servico da humanidade
TDC2019 Intel Software Day - Visao Computacional e IA a servico da humanidade
 
TDC2019 Intel Software Day - Tecnicas de Programacao Paralela em Machine Lear...
TDC2019 Intel Software Day - Tecnicas de Programacao Paralela em Machine Lear...TDC2019 Intel Software Day - Tecnicas de Programacao Paralela em Machine Lear...
TDC2019 Intel Software Day - Tecnicas de Programacao Paralela em Machine Lear...
 
TDC2019 Intel Software Day - ACATE - Cases de Sucesso
TDC2019 Intel Software Day - ACATE - Cases de SucessoTDC2019 Intel Software Day - ACATE - Cases de Sucesso
TDC2019 Intel Software Day - ACATE - Cases de Sucesso
 
TDC2019 Intel Software Day - Otimizacao grafica com o Intel GPA
TDC2019 Intel Software Day - Otimizacao grafica com o Intel GPATDC2019 Intel Software Day - Otimizacao grafica com o Intel GPA
TDC2019 Intel Software Day - Otimizacao grafica com o Intel GPA
 
TDC2019 Intel Software Day - Deteccao de objetos em tempo real com OpenVino
TDC2019 Intel Software Day - Deteccao de objetos em tempo real com OpenVinoTDC2019 Intel Software Day - Deteccao de objetos em tempo real com OpenVino
TDC2019 Intel Software Day - Deteccao de objetos em tempo real com OpenVino
 
TDC2019 Intel Software Day - OpenCV: Inteligencia artificial e Visao Computac...
TDC2019 Intel Software Day - OpenCV: Inteligencia artificial e Visao Computac...TDC2019 Intel Software Day - OpenCV: Inteligencia artificial e Visao Computac...
TDC2019 Intel Software Day - OpenCV: Inteligencia artificial e Visao Computac...
 
TDC2019 Intel Software Day - Inferencia de IA em edge devices
TDC2019 Intel Software Day - Inferencia de IA em edge devicesTDC2019 Intel Software Day - Inferencia de IA em edge devices
TDC2019 Intel Software Day - Inferencia de IA em edge devices
 
Trilha BigData - Banco de Dados Orientado a Grafos na Seguranca Publica
Trilha BigData - Banco de Dados Orientado a Grafos na Seguranca PublicaTrilha BigData - Banco de Dados Orientado a Grafos na Seguranca Publica
Trilha BigData - Banco de Dados Orientado a Grafos na Seguranca Publica
 
Trilha .Net - Programacao funcional usando f#
Trilha .Net - Programacao funcional usando f#Trilha .Net - Programacao funcional usando f#
Trilha .Net - Programacao funcional usando f#
 
TDC2018SP | Trilha Go - Case Easylocus
TDC2018SP | Trilha Go - Case EasylocusTDC2018SP | Trilha Go - Case Easylocus
TDC2018SP | Trilha Go - Case Easylocus
 
TDC2018SP | Trilha Modern Web - Para onde caminha a Web?
TDC2018SP | Trilha Modern Web - Para onde caminha a Web?TDC2018SP | Trilha Modern Web - Para onde caminha a Web?
TDC2018SP | Trilha Modern Web - Para onde caminha a Web?
 
TDC2018SP | Trilha Go - Clean architecture em Golang
TDC2018SP | Trilha Go - Clean architecture em GolangTDC2018SP | Trilha Go - Clean architecture em Golang
TDC2018SP | Trilha Go - Clean architecture em Golang
 
TDC2018SP | Trilha Go - "Go" tambem e linguagem de QA
TDC2018SP | Trilha Go - "Go" tambem e linguagem de QATDC2018SP | Trilha Go - "Go" tambem e linguagem de QA
TDC2018SP | Trilha Go - "Go" tambem e linguagem de QA
 
TDC2018SP | Trilha Mobile - Digital Wallets - Seguranca, inovacao e tendencia
TDC2018SP | Trilha Mobile - Digital Wallets - Seguranca, inovacao e tendenciaTDC2018SP | Trilha Mobile - Digital Wallets - Seguranca, inovacao e tendencia
TDC2018SP | Trilha Mobile - Digital Wallets - Seguranca, inovacao e tendencia
 
TDC2018SP | Trilha .Net - Real Time apps com Azure SignalR Service
TDC2018SP | Trilha .Net - Real Time apps com Azure SignalR ServiceTDC2018SP | Trilha .Net - Real Time apps com Azure SignalR Service
TDC2018SP | Trilha .Net - Real Time apps com Azure SignalR Service
 
TDC2018SP | Trilha .Net - Passado, Presente e Futuro do .NET
TDC2018SP | Trilha .Net - Passado, Presente e Futuro do .NETTDC2018SP | Trilha .Net - Passado, Presente e Futuro do .NET
TDC2018SP | Trilha .Net - Passado, Presente e Futuro do .NET
 
TDC2018SP | Trilha .Net - Novidades do C# 7 e 8
TDC2018SP | Trilha .Net - Novidades do C# 7 e 8TDC2018SP | Trilha .Net - Novidades do C# 7 e 8
TDC2018SP | Trilha .Net - Novidades do C# 7 e 8
 
TDC2018SP | Trilha .Net - Obtendo metricas com TDD utilizando build automatiz...
TDC2018SP | Trilha .Net - Obtendo metricas com TDD utilizando build automatiz...TDC2018SP | Trilha .Net - Obtendo metricas com TDD utilizando build automatiz...
TDC2018SP | Trilha .Net - Obtendo metricas com TDD utilizando build automatiz...
 
TDC2018SP | Trilha .Net - .NET funcional com F#
TDC2018SP | Trilha .Net - .NET funcional com F#TDC2018SP | Trilha .Net - .NET funcional com F#
TDC2018SP | Trilha .Net - .NET funcional com F#
 
TDC2018SP | Trilha .Net - Crie SPAs com Razor e C# usando Blazor em .Net Core
TDC2018SP | Trilha .Net - Crie SPAs com Razor e C# usando Blazor  em .Net CoreTDC2018SP | Trilha .Net - Crie SPAs com Razor e C# usando Blazor  em .Net Core
TDC2018SP | Trilha .Net - Crie SPAs com Razor e C# usando Blazor em .Net Core
 

Kürzlich hochgeladen

1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
QucHHunhnh
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
QucHHunhnh
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
heathfieldcps1
 

Kürzlich hochgeladen (20)

Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-IIFood Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701
 

TDC2016POA | Trilha Programacao Funcional - Ramda JS como alternativa a underscore e lodash

  • 1. Globalcode – Open4education Ramda Derek Stavis Software Engineer
  • 2. Globalcode – Open4education Who? Derek Stavis github.com/derekstavis Software Engineer Ruby, JavaScript, Python, C Node, React & Webpack Advocate
  • 3. Globalcode – Open4education Have you been using functional helper libraries?
  • 7. Globalcode – Open4education Those are really good libraries
  • 8. Globalcode – Open4education Weren't designed with a functional mindset from day 0
  • 9. Globalcode – Open4education Ramda A functional programming library http://ramdajs.com
  • 10. Globalcode – Open4education Meet Ramda Emphasizes a purer functional style Immutability and side-effect free functions Ramda functions are automatically curried Argument ordering convenient to currying Keep rightmost the data to be operated
  • 11. Globalcode – Open4education Small, single-responsibility and reusable functions
  • 13. Globalcode – Open4education Ramda shines on currying var names = [ { name: 'Pablo' }, { name: 'Escobar' }, { name: 'Gaviria' } ] var getName = R.prop('name') var pickNames = R.map(getName, names) pickNames() => [ 'Pablo', 'Escobar', 'Gaviria' ]
  • 14. Globalcode – Open4education Ramda shines on currying var names = [ { name: 'Pablo' }, { name: 'Escobar' }, { name: 'Gaviria' } ] var getName = R.prop('name') var pickNames = R.map(getName) pickNames(names) => [ 'Pablo', 'Escobar', 'Gaviria' ]
  • 16. Globalcode – Open4education Currying was named after Haskell Curry One of the first to investigate such technique
  • 17. Globalcode – Open4education Turn a function that expects multiple arguments into one that, when supplied fewer arguments, returns a new function that awaits the remaining ones
  • 18. Globalcode – Open4education Ramda is about currying const cookPasta = R.curry((water, heat, pasta) => { ... }) // Have everything needed cookPasta (water, heat, pasta) // Forgot to buy pasta cookPasta (water, heat)(pasta) // No gas and no pasta cookPasta (water)(heat, pasta) // Had to go twice to supermarket cookPasta (water)(heat)(pasta)
  • 20. Globalcode – Open4education Ramda is all curried 😎
  • 22. Globalcode – Open4education Ramda is all curried R.add(2, 3) //=> 5 R.add(7)(10) //=> 17 R.contains(2, [1, 2, 3]) //=> true R.contains(1)([1, 2, 3]) //=> true R.replace(/foo/g, 'bar', 'foo foo') //=> 'bar bar' R.replace(/foo/g, 'bar')('foo foo') //=> 'bar bar' R.replace(/foo/g)('bar')('foo foo') //=> 'bar bar'
  • 23. Globalcode – Open4education Apply the parameters left-to-right when you have them 👉
  • 24. Globalcode – Open4education But what if you'd like to apply the leftmost or intermediate arguments before the rightmost?
  • 25. Globalcode – Open4education Leave argument placeholders ✍
  • 26. Globalcode – Open4education Functional placeholder R.minus(R.__, 5)(10) //=> 5 R.divide(R.__, 5)(10) //=> 17 R.contains(R.__, [1, 2, 3])(2) //=> true R.contains(R.__, [1, 2, 3])(1) //=> true R.contains(R.__, R.__)(1)([1, 2, 3]) //=> true
  • 27. Globalcode – Open4education Or do partial application
  • 28. Globalcode – Open4education Ramda does partial application both left-to-right and right-to-left
  • 29. Globalcode – Open4education In fact, there's no currying as in theoretical math, Ramda currying is, in reality, partial application
  • 30. Globalcode – Open4education Partial application const greet = (salutation, title, name) => `${salutation}, ${title} ${name}!` const greetMrCrowley = R.partialRight(greet, ['Mr.', 'Crowley']) greetMrCrowley('Hello') //=> 'Hello, Mr. Crowley!' const greetMr = R.partial(greet, ['Hello', 'Mr.']) const greetMs = R.partial(greet, ['Hello', 'Ms.']) greetMr('Mendel') // => 'Hello, Mr. Mendel' greetMs('Curie') // => 'Hello, Ms. Curie'
  • 31. Globalcode – Open4education Ramda also makes available some cool and very useful functions
  • 32. Globalcode – Open4education Avoiding you to rewrite the same stuff that you always have to
  • 33. Globalcode – Open4education Ramda functions are divided into various categories
  • 34. Globalcode – Open4education Ramda functions categories Function Math List Logic Object Relation
  • 35. Globalcode – Open4education Function functions // Always return the same thing, ignoring arguments const name = R.always('Derek') name('Willian') //=> Derek // Functional if then else, a.k.a. Maybe Monad const findName = R.ifElse( R.has('name'), R.prop('name'), R.always('No name') ) findName({ title: 'Mr.', name: 'Derek' }) //=> Derek findName({ title: 'Mr.' }) //=> No name // Pipe functions left-to-right. First function can have any arity // Others must have arity of exactly one const calculate = R.pipe(Math.pow, R.negate, R.inc); calculate(3, 2); // -(3^2) + 1
  • 36. Globalcode – Open4education Math functions // Addition R.add(1, 2) //=> 3 // Subtraction R.subtract(2, 1) //=> 1 // Sum all elements R.sum([1, 1, 1]) //=> 3 // Increment R.inc(41) //=> 42 // Decrement R.dec(43) //=> 42 // Calculate the mean R.mean([2, 7, 9]) //=> 6
  • 37. Globalcode – Open4education List functions // Check if all elements match a predicate R.all(R.gt(4), [1, 2, 3]) //=> true // Check if a number is inside a list R.contains(3, [1, 2, 3]) // Drop elements from start R.drop(1, ['foo', 'bar', 'baz']) //=> ['bar', 'baz'] // Find elements using a predicate const list = [{a: 1}, {a: 2}, {a: 3}] R.find(R.propEq('a', 2))(list) //=> {a: 2} R.find(R.propEq('a', 4))(list) //=> undefined // Flatten a list of list into a single list const list = [1, 2, [3, 4], 5, [6, [7, 8, [9, [10, 11], 12]]]] R.flatten(list) //=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
  • 38. Globalcode – Open4education Logic functions // Combine predicates into a single function var gt10 = x => x > 10 var even = x => x % 2 === 0 var gt10even = R.both(gt10, even) gt10even(100) //=> true gt10even(101) //=> false // Functional switch case (aka. pattern matching?) var whatHappensAtTemperature = R.cond([ [R.equals(0), R.always('water freezes at 0°C')], [R.equals(100), R.always('water boils at 100°C')], [R.T, temp => 'nothing special happens at ' + temp + '°C'] ]) whatHappensAtTemperature(0) //=> 'water freezes at 0°C' whatHappensAtTemperature(50) //=> 'nothing special happens at 50°C' whatHappensAtTemperature(100) //=> 'water boils at 100°C'
  • 39. Globalcode – Open4education Object functions // Add a key and value to an already existing object R.assoc('c', 3, {a: 1, b: 2}) //=> {a: 1, b: 2, c: 3} // Remove a key from an already existing object R.dissoc('b', {a: 1, b: 2, c: 3}) //=> {a: 1, c: 3} // Do the same with a nested path R.assocPath(['a', 'b', 'c'], 42, {a: {b: {c: 0}}}) //=> {a: {b: {c: 42}}} // Check if an object contains a key var hasName = R.has('name') hasName({name: 'alice'}) //=> true hasName({name: 'bob'}) //=> true hasName({}) //=> false // Pick some properties from objects var abby = {name: 'Abby', age: 7, hair: 'blond', grade: 2} var fred = {name: 'Fred', age: 12, hair: 'brown', grade: 7} R.project(['name', 'grade'], [abby, fred]) //=> [{name: 'Abby', grade: 2}, {name: 'Fred', grade: 7}]
  • 40. Globalcode – Open4education Relation functions // Lots of comparison functions // Kinda tricky, but also kinda natural R.gt(2, 1) // 2 > 1 R.gt(2, 2) // 2 > 2 R.gte(2, 2) // 2 >= 2 R.gte(3, 2) // 3 >= 2 R.lt(2, 1) // 2 < 1 R.lt(2, 2) // 2 < 2 R.lte(2, 2) // 2 <= 2 R.lte(3, 2) // 3 <= 2 // Restrict a number to a range R.clamp(1, 10, -1) // => 1 R.clamp(1, 10, 11) // => 10 // Intersect two lists R.intersection([1,2,3,4], [7,6,4,3]) //=> [4, 3]
  • 41. Globalcode – Open4education Ramda works well with Promise
  • 42. Globalcode – Open4education Ramda and Promises app.get('/v1/plants/:id', auth.active, (req, res) => { db.plants.find({ id: req.params.id }) .then(R.head) .then(R.bind(res.send, res)) })
  • 43. Globalcode – Open4education Ramda and Promises function timesValues (number) { return spot(number) .then(spot => db.collection('zone_type_values') .findOne({ id: spot.zone_type_value_id }) .then(R.prop('time_values')) .then(R.assoc('timesValues', R.__, spot)) .then(R.pickAll(['id', 'name', 'timesValues'])) ) }
  • 44. Globalcode – Open4education Thanks for watching Questions? github.com/derekstavis twitter.com/derekstavis facebook.com/derekstavis