SlideShare a Scribd company logo
1 of 44
Download to read offline
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

More Related Content

What's hot

Xlab #1: Advantages of functional programming in Java 8
Xlab #1: Advantages of functional programming in Java 8Xlab #1: Advantages of functional programming in Java 8
Xlab #1: Advantages of functional programming in Java 8XSolve
 
Being functional in PHP (DPC 2016)
Being functional in PHP (DPC 2016)Being functional in PHP (DPC 2016)
Being functional in PHP (DPC 2016)David de Boer
 
ITT 2015 - Saul Mora - Object Oriented Function Programming
ITT 2015 - Saul Mora - Object Oriented Function ProgrammingITT 2015 - Saul Mora - Object Oriented Function Programming
ITT 2015 - Saul Mora - Object Oriented Function ProgrammingIstanbul Tech Talks
 
FunctionalJS - George Shevtsov
FunctionalJS - George ShevtsovFunctionalJS - George Shevtsov
FunctionalJS - George ShevtsovGeorgiy Shevtsov
 
Programming with Python and PostgreSQL
Programming with Python and PostgreSQLProgramming with Python and PostgreSQL
Programming with Python and PostgreSQLPeter Eisentraut
 
名古屋SGGAE/J勉強会 Grails、Gaelykでハンズオン
名古屋SGGAE/J勉強会 Grails、Gaelykでハンズオン名古屋SGGAE/J勉強会 Grails、Gaelykでハンズオン
名古屋SGGAE/J勉強会 Grails、GaelykでハンズオンTsuyoshi Yamamoto
 
Python postgre sql a wonderful wedding
Python postgre sql   a wonderful weddingPython postgre sql   a wonderful wedding
Python postgre sql a wonderful weddingStéphane Wirtel
 
TDC2016SP - Trilha Frameworks JavaScript
TDC2016SP - Trilha Frameworks JavaScriptTDC2016SP - Trilha Frameworks JavaScript
TDC2016SP - Trilha Frameworks JavaScripttdc-globalcode
 
Hypers and Gathers and Takes! Oh my!
Hypers and Gathers and Takes! Oh my!Hypers and Gathers and Takes! Oh my!
Hypers and Gathers and Takes! Oh my!Workhorse Computing
 
Programmation fonctionnelle en JavaScript
Programmation fonctionnelle en JavaScriptProgrammation fonctionnelle en JavaScript
Programmation fonctionnelle en JavaScriptLoïc Knuchel
 
Scalaz By Example (An IO Taster) -- PDXScala Meetup Jan 2014
Scalaz By Example (An IO Taster) -- PDXScala Meetup Jan 2014Scalaz By Example (An IO Taster) -- PDXScala Meetup Jan 2014
Scalaz By Example (An IO Taster) -- PDXScala Meetup Jan 2014Susan Potter
 
The Easy-Peasy-Lemon-Squeezy, Statically-Typed, Purely Functional Programming...
The Easy-Peasy-Lemon-Squeezy, Statically-Typed, Purely Functional Programming...The Easy-Peasy-Lemon-Squeezy, Statically-Typed, Purely Functional Programming...
The Easy-Peasy-Lemon-Squeezy, Statically-Typed, Purely Functional Programming...John De Goes
 
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-Tsuyoshi Yamamoto
 
Javascript ES6 generators
Javascript ES6 generatorsJavascript ES6 generators
Javascript ES6 generatorsRamesh Nair
 
"PostgreSQL and Python" Lightning Talk @EuroPython2014
"PostgreSQL and Python" Lightning Talk @EuroPython2014"PostgreSQL and Python" Lightning Talk @EuroPython2014
"PostgreSQL and Python" Lightning Talk @EuroPython2014Henning Jacobs
 

What's hot (18)

Xlab #1: Advantages of functional programming in Java 8
Xlab #1: Advantages of functional programming in Java 8Xlab #1: Advantages of functional programming in Java 8
Xlab #1: Advantages of functional programming in Java 8
 
Being functional in PHP (DPC 2016)
Being functional in PHP (DPC 2016)Being functional in PHP (DPC 2016)
Being functional in PHP (DPC 2016)
 
ITT 2015 - Saul Mora - Object Oriented Function Programming
ITT 2015 - Saul Mora - Object Oriented Function ProgrammingITT 2015 - Saul Mora - Object Oriented Function Programming
ITT 2015 - Saul Mora - Object Oriented Function Programming
 
はじめてのGroovy
はじめてのGroovyはじめてのGroovy
はじめてのGroovy
 
FunctionalJS - George Shevtsov
FunctionalJS - George ShevtsovFunctionalJS - George Shevtsov
FunctionalJS - George Shevtsov
 
Programming with Python and PostgreSQL
Programming with Python and PostgreSQLProgramming with Python and PostgreSQL
Programming with Python and PostgreSQL
 
名古屋SGGAE/J勉強会 Grails、Gaelykでハンズオン
名古屋SGGAE/J勉強会 Grails、Gaelykでハンズオン名古屋SGGAE/J勉強会 Grails、Gaelykでハンズオン
名古屋SGGAE/J勉強会 Grails、Gaelykでハンズオン
 
Python postgre sql a wonderful wedding
Python postgre sql   a wonderful weddingPython postgre sql   a wonderful wedding
Python postgre sql a wonderful wedding
 
TDC2016SP - Trilha Frameworks JavaScript
TDC2016SP - Trilha Frameworks JavaScriptTDC2016SP - Trilha Frameworks JavaScript
TDC2016SP - Trilha Frameworks JavaScript
 
Hypers and Gathers and Takes! Oh my!
Hypers and Gathers and Takes! Oh my!Hypers and Gathers and Takes! Oh my!
Hypers and Gathers and Takes! Oh my!
 
Programmation fonctionnelle en JavaScript
Programmation fonctionnelle en JavaScriptProgrammation fonctionnelle en JavaScript
Programmation fonctionnelle en JavaScript
 
Scalaz By Example (An IO Taster) -- PDXScala Meetup Jan 2014
Scalaz By Example (An IO Taster) -- PDXScala Meetup Jan 2014Scalaz By Example (An IO Taster) -- PDXScala Meetup Jan 2014
Scalaz By Example (An IO Taster) -- PDXScala Meetup Jan 2014
 
Coffee script
Coffee scriptCoffee script
Coffee script
 
Introduction kot iin
Introduction kot iinIntroduction kot iin
Introduction kot iin
 
The Easy-Peasy-Lemon-Squeezy, Statically-Typed, Purely Functional Programming...
The Easy-Peasy-Lemon-Squeezy, Statically-Typed, Purely Functional Programming...The Easy-Peasy-Lemon-Squeezy, Statically-Typed, Purely Functional Programming...
The Easy-Peasy-Lemon-Squeezy, Statically-Typed, Purely Functional Programming...
 
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
 
Javascript ES6 generators
Javascript ES6 generatorsJavascript ES6 generators
Javascript ES6 generators
 
"PostgreSQL and Python" Lightning Talk @EuroPython2014
"PostgreSQL and Python" Lightning Talk @EuroPython2014"PostgreSQL and Python" Lightning Talk @EuroPython2014
"PostgreSQL and Python" Lightning Talk @EuroPython2014
 

Viewers also liked

Packing it all: JavaScript module bundling from 2000 to now
Packing it all: JavaScript module bundling from 2000 to nowPacking it all: JavaScript module bundling from 2000 to now
Packing it all: JavaScript module bundling from 2000 to nowDerek Willian Stavis
 
WHY JAVASCRIPT FUNCTIONAL PROGRAMMING IS SO HARD?
WHY JAVASCRIPT FUNCTIONAL PROGRAMMING IS SO HARD? WHY JAVASCRIPT FUNCTIONAL PROGRAMMING IS SO HARD?
WHY JAVASCRIPT FUNCTIONAL PROGRAMMING IS SO HARD? reactima
 
Lars thorup-react-and-redux-2016-09
Lars thorup-react-and-redux-2016-09Lars thorup-react-and-redux-2016-09
Lars thorup-react-and-redux-2016-09BestBrains
 
Warsaw Frontend Meetup #1 - Webpack
Warsaw Frontend Meetup #1 - WebpackWarsaw Frontend Meetup #1 - Webpack
Warsaw Frontend Meetup #1 - WebpackRadosław Rosłaniec
 
Webpack Tutorial, Uppsala JS
Webpack Tutorial, Uppsala JSWebpack Tutorial, Uppsala JS
Webpack Tutorial, Uppsala JSEmil Öberg
 
Webpack Introduction
Webpack IntroductionWebpack Introduction
Webpack IntroductionAnjali Chawla
 
Forget Grunt and Gulp! Webpack and NPM rule them all!
Forget Grunt and Gulp! Webpack and NPM rule them all!Forget Grunt and Gulp! Webpack and NPM rule them all!
Forget Grunt and Gulp! Webpack and NPM rule them all!Derek Willian Stavis
 
Webpack and Web Performance Optimization
Webpack and Web Performance OptimizationWebpack and Web Performance Optimization
Webpack and Web Performance OptimizationChen-Tien Tsai
 
Webpack: your final module bundler
Webpack: your final module bundlerWebpack: your final module bundler
Webpack: your final module bundlerAndrea Giannantonio
 
Packing for the Web with Webpack
Packing for the Web with WebpackPacking for the Web with Webpack
Packing for the Web with WebpackThiago Temple
 
webpack 入門
webpack 入門webpack 入門
webpack 入門Anna Su
 
前端界流傳的神奇招式
前端界流傳的神奇招式前端界流傳的神奇招式
前端界流傳的神奇招式Anna Su
 
Webpack
Webpack Webpack
Webpack DataArt
 

Viewers also liked (17)

Packing it all: JavaScript module bundling from 2000 to now
Packing it all: JavaScript module bundling from 2000 to nowPacking it all: JavaScript module bundling from 2000 to now
Packing it all: JavaScript module bundling from 2000 to now
 
Hardcore functional programming
Hardcore functional programmingHardcore functional programming
Hardcore functional programming
 
WHY JAVASCRIPT FUNCTIONAL PROGRAMMING IS SO HARD?
WHY JAVASCRIPT FUNCTIONAL PROGRAMMING IS SO HARD? WHY JAVASCRIPT FUNCTIONAL PROGRAMMING IS SO HARD?
WHY JAVASCRIPT FUNCTIONAL PROGRAMMING IS SO HARD?
 
Lars thorup-react-and-redux-2016-09
Lars thorup-react-and-redux-2016-09Lars thorup-react-and-redux-2016-09
Lars thorup-react-and-redux-2016-09
 
Warsaw Frontend Meetup #1 - Webpack
Warsaw Frontend Meetup #1 - WebpackWarsaw Frontend Meetup #1 - Webpack
Warsaw Frontend Meetup #1 - Webpack
 
Webpack DevTalk
Webpack DevTalkWebpack DevTalk
Webpack DevTalk
 
Webpack Tutorial, Uppsala JS
Webpack Tutorial, Uppsala JSWebpack Tutorial, Uppsala JS
Webpack Tutorial, Uppsala JS
 
Webpack Introduction
Webpack IntroductionWebpack Introduction
Webpack Introduction
 
Forget Grunt and Gulp! Webpack and NPM rule them all!
Forget Grunt and Gulp! Webpack and NPM rule them all!Forget Grunt and Gulp! Webpack and NPM rule them all!
Forget Grunt and Gulp! Webpack and NPM rule them all!
 
Webpack and Web Performance Optimization
Webpack and Web Performance OptimizationWebpack and Web Performance Optimization
Webpack and Web Performance Optimization
 
Webpack: your final module bundler
Webpack: your final module bundlerWebpack: your final module bundler
Webpack: your final module bundler
 
Webpack slides
Webpack slidesWebpack slides
Webpack slides
 
Packing for the Web with Webpack
Packing for the Web with WebpackPacking for the Web with Webpack
Packing for the Web with Webpack
 
webpack 入門
webpack 入門webpack 入門
webpack 入門
 
前端界流傳的神奇招式
前端界流傳的神奇招式前端界流傳的神奇招式
前端界流傳的神奇招式
 
Advanced webpack
Advanced webpackAdvanced webpack
Advanced webpack
 
Webpack
Webpack Webpack
Webpack
 

Similar to Ramda, a functional JavaScript library

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 Wsloffenauer
 
r,rstats,r language,r packages
r,rstats,r language,r packagesr,rstats,r language,r packages
r,rstats,r language,r packagesAjay Ohri
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing UpDavid Padbury
 
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 RubyVysakh Sreenivasan
 
GPars For Beginners
GPars For BeginnersGPars For Beginners
GPars For BeginnersMatt Passell
 
Mongoskin - Guilin
Mongoskin - GuilinMongoskin - Guilin
Mongoskin - GuilinJackson Tian
 
Introducing PHP Latest Updates
Introducing PHP Latest UpdatesIntroducing PHP Latest Updates
Introducing PHP Latest UpdatesIftekhar Eather
 
Metaprogramovanie #1
Metaprogramovanie #1Metaprogramovanie #1
Metaprogramovanie #1Jano Suchal
 
Ruby from zero to hero
Ruby from zero to heroRuby from zero to hero
Ruby from zero to heroDiego Lemos
 
Functional programming in javascript
Functional programming in javascriptFunctional programming in javascript
Functional programming in javascriptBoris Burdiliak
 
Functional techniques in Ruby
Functional techniques in RubyFunctional techniques in Ruby
Functional techniques in Rubyerockendude
 
Functional techniques in Ruby
Functional techniques in RubyFunctional techniques in Ruby
Functional techniques in Rubyerockendude
 
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.netProgrammer Blog
 
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 RLun-Hsien Chang
 

Similar to Ramda, a functional JavaScript library (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
 
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
 
R basics
R basicsR basics
R basics
 

Recently uploaded

Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilV3cube
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 

Recently uploaded (20)

Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 

Ramda, a functional JavaScript library

  • 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