SlideShare ist ein Scribd-Unternehmen logo
1 von 59
Downloaden Sie, um offline zu lesen
Functional JavaScript
for everyone
Bartek Witczak
1/320
http://te.xel.io/posts/2015-02-22-category-theory-and-human-behavior.html
https://prateekvjoshi.com/2014/11/01/functors-in-c/
Functions
function youngerThan(limit, age) {
return age < limit
}
function youngerThan(limit) {
return function(age) {
return age < limit
}
}
function youngerThan(limit) {
return function(age) {
return age < limit
}
}
const youngerThanMe = youngerThan(28)
...
people.map(youngerThanMe)
In programming language design, a first-class citizen (…) is an
entity which supports all the operations generally available to
other entities. These operations typically include being passed
as an argument, returned from a function, and assigned to a
variable
let languages = ['JavaScript', 'Scala', 'Go']
...
...
...
...
let divs = []
for(let i = 0; i < languages.length; i++) {
divs.push(`<div>${langs[i]}</div>`)
}
let languages = ['JavaScript', 'Scala', 'Go']
languages.push('Java')
languages.push('Ruby')
languages.splice(0, 3)
let divs = []
for(let i = 0; i < languages.length; i++) {
divs.push(`<div>${languages[i]}</div>`)
}
const languages = Immutable.List.of(
‘JavaScript',
‘Scala',
‘Go'
)
...
...
let divs = []
for(let i = 0; i < languages.length; i++)
{
divs.push(`<div>${languages[i]}</div>`)
}
• always evaluates to same result for the same
input
• evaluation does not cause any semantically
observable side effects
Pure function
let user = {...}
function createMessage(text) {
const message = Db.save(text)
return message
}
function sendMessage(text) {
const message = createMessage(text)
const messageId = MessageService.send(message, user)
return messageId
}
IMPURE
function createMessage(Db, text) {
const message = Db.save(text)
return message
}
function sendMessage(Db, MessageService, text, user) {
const message = createMessage(Db, text)
const messageId = MessageService.send(message, user)
return messageId
}
PURE
function createMessage(Db, text) {
const message = Db.save(text)
return message
}
function sendMessage(Db, MessageService, text, user) {
const message = createMessage(Db, text)
const messageId = MessageService.send(message, user)
return messageId
}
Explicit dependency / Self-documenting
Testable
function createMessage(Db, text) {
const message = Db.save(text)
return message
}
function sendMessage(Db, MessageService, text, user) {
const message = createMessage(Db, text)
const messageId = MessageService.send(message, user)
return messageId
}
Resonable
function createMessage(Db, text) {
const message = Db.save(text)
return message
}
function sendMessage(Db, MessageService, text, user) {
const message = createMessage(Db, text)
const messageId = MessageService.send(message, user)
return messageId
}
The problem with object-oriented languages is they’ve got all
this implicit environment that they carry around with them. You
wanted a banana but what you got was a gorilla holding the
banana... and the entire jungle
Joe Armstrong, Erlang creator
Currying
f ( x, y ) === f ( x ) ( y )
function add(x, y) {
return x + y
}
add(2, 3)
function curried_add (x) {
return function (y) {
return x + y
}
}
curried_add(2)(3)
const increment = curried_add(1)
increment(5)
peopleAge.map(increment)
const add10 = curried_add(10)
add10(15)
export const create = (fetch) => {
return {
...
post: (url, data, token) => {
const secureHeader = token ? { 'SECURE-TOKEN':
token } : {}
return Q(fetch(url, {
method: 'post',
headers: _.assign({
'Accept': 'application/json',
'Content-Type': 'application/json'
}, secureHeader),
body: JSON.stringify(data)
}))
}
...
}
export default create(fetch)
const token = '1jflann24kh11;2114fanakf'
http.post(someURL, { user: 'Henry' }, token)
return {
...
post: (token, url, data) => {
...
post(token)(url)(data)
currying
const createSecured = (http, token) => {
...
post: http.post(token)
...
}
sercureHttp.post(someURL)({ user: 'Henry' })
No more loops
const languages = ['JavaScript', 'Scala', 'Haskell']
const divs = []
for(let i = 0; i < languages.length; i++) {
divs.push(`<div>${languages[i]}</div>`)
}
const languages = ['JavaScript', 'Scala', 'Haskell']
const divs = languages.map(l => `<div>${l}</div>`)
const dimensions = [100, 231, 84]
const sum = 0
for(let i = 0; i < dimensions.length; i++) {
sum += dimensions[i]
}
const dimensions = [100, 231, 84]
const sum = dimensions.reduce((a, b) => a + b, 0)
const people = [{name: 'Henry', age: 21},
... ]
const adults = []
for(let i = 0; i < people.length; i++) {
if(people[i].age >= 18) {
adults.push(people[i])
}
}
const people = [{name: 'Henry', age: 21},
... ]
const adults = people.filter(p => p.age >= 18)
Function composition
f(g(x)) === (f ∘ g)(x)
function compose(f, g) {
return function(x) {
return f(g(x))
}
}
const add2 = (x) => x + 2
const multiplyBy2 = (x) => x * 2
multiplyBy2(add2(3))
const add2ThenMultiplyBy2 = compose(multiplyBy2, add2)
add2ThenMultiplyBy2(3)
function convertToAlbums(json) {
const artist = extractArtist(json)
const album = ...
return album
}
function extractTracks(album) {
const rawTracks = album.tracks
const tracks = ...
return tracks
}
function trackElem(track) {
return `<li>${track.name} - ${track.duration}</li>`
}
const tracks = compose(extractTracks, convertToAlbums)
const tracksFromJson = compose(map(trackElem), tracks)
tracksFromJson(albumJson)
Burritos & other boxes
function Burrito(x) => ({
map: f => Burrito(f(x))
})
function Burrito(x) => ({
map: f => Burrito(f(x))
})
const food = ...
Burrito(food)
.map(f => return peel(f))
.map(f => return chop(f))
.map(f => return cook(f))
///////
// Burrito(cooked(chopped(peeled(food))))
///////
function Burrito(x) => ({
map: f => Burrito(f(x)),
fold: f => f(x)
})
const food = ...
Burrito(food)
.map(x => return peel(x))
.map(x => return chop(x))
.map(x => return cook(x))
.fold(x => return grill(x))
///////
// grilled(cooked(chopped(peeled(food))))
///////
Burrito we all know
const hours = [
'2017-03-31T10:41:47.707Z',
'2017-03-31T10:41:47.707Z',
'2017-03-31T10:41:47.707Z'
]
hours
.map(h => moment.utc(h))
.map(m => new Date(
m.year(),
m.month(),
m.date(),
m.hour(),
m.minutes()
))
And I say MAYBE
const find = (list, predicate) => {
for (let i = 0; i < list.length; ++i) {
const item = list[i]
if (predicate(item)) {
return item
}
}
return null
}
const render = (text) => (`<div>That one is AWESOME ${text}!!!</div>`)
const langs = ['JS', 'Haskell', 'Scala']
const js = find(langs, l => return l.length === 2)
if (js !== null) {
return '<div>hmm</div>'
} else {
render(js)
}
//OR
const render = (text) => {
if(text == null) {
return '<div>hmm</div>'
} else {
return `<div>That one is AWESOME ${text}!!!</div>`
}
}
const js = find(langs, l => return l === 'JS')
render(js)
const find = (list, predicate) => {
for (let i = 0; i < list.length; ++i) {
const item = list[i]
if (predicate(item)) {
return item
}
}
return null
}
const find = (list, predicate) => {
for (let i = 0; i < list.length; ++i) {
const item = list[i]
if (predicate(item)) {
return Maybe.Just(item)
}
}
return Maybe.Nothing()
}
and I say MAYBE
const render = (text) => (`<div>That one is AWESOME ${text}!!!</div>`)
const langs = ['JS', 'Haskell', 'Scala']
const best = find(langs, l => return l === 'JS')
best
.map(render)
.getOrElse('<div>hmm</div>)
Don’t try too hard
const tripIds = reduce(trips, (acc, t) => {
acc.push(t._id)
return acc
}, [])
const tripsIds = map(trips, t => t._id)
const tripsIds = map(trips, ’_id’)
OR
If you have a hammer,
everything looks like a
nail.
Real life fluff
function createTimeslots(trip) {
const slots = _.reduce(trip.days, (acc, d) => {
let [startHour, startMinutes] = _.map(d.startHour.split(':'), i =>
parseInt(i, 10))
startMinutes = normalizeStartMinutes(startMinutes)
const start = ...
const [endHour, endMinutes] = _.map(d.endHour.split(':'), i =>
parseInt(i, 10))
const end = ...
/// GIVE ME MORE
return acc
}, [])
return slots
}
function createTimeslots(trip) {
///GIVE ME MORE
}
function createTimeslotsFromTrips(trips) {
return map(trips, createTimeslots).flatten()
}
function createTimeslotsFromTrips(trips) {
return flatMap(trips, createTimeslots)
}
function createTimeslotsFromTrips(trips) {
return flatMap(createTimeslots, trips)
}
function createTimeslotsFromTrips(trips) {
return flatMap(createTimeslots)(trips)
}
const createTimeslotsFromTrips = _.flatMap(createTimeslots)
Bartek Witczak
@bartekwitczak
bartek@dayone.pl

Weitere ähnliche Inhalte

Was ist angesagt?

20160616技術會議
20160616技術會議20160616技術會議
20160616技術會議Jason Kuan
 
Rデバッグあれこれ
RデバッグあれこれRデバッグあれこれ
RデバッグあれこれTakeshi Arabiki
 
Rのスコープとフレームと環境と
Rのスコープとフレームと環境とRのスコープとフレームと環境と
Rのスコープとフレームと環境とTakeshi Arabiki
 
CUDA First Programs: Computer Architecture CSE448 : UAA Alaska : Notes
CUDA First Programs: Computer Architecture CSE448 : UAA Alaska : NotesCUDA First Programs: Computer Architecture CSE448 : UAA Alaska : Notes
CUDA First Programs: Computer Architecture CSE448 : UAA Alaska : NotesSubhajit Sahu
 
Secuencias Recursivas, Sucesiones Recursivas & Progresiones con Geogebra
Secuencias Recursivas, Sucesiones Recursivas & Progresiones con GeogebraSecuencias Recursivas, Sucesiones Recursivas & Progresiones con Geogebra
Secuencias Recursivas, Sucesiones Recursivas & Progresiones con GeogebraJose Perez
 
Flexible Data Representation with Fixpoint Types
Flexible Data Representation with Fixpoint TypesFlexible Data Representation with Fixpoint Types
Flexible Data Representation with Fixpoint TypesDave Cleaver
 
2017-08-22 Python×Djangoで作るHR Techサービスのメリット・デメリット
2017-08-22 Python×Djangoで作るHR Techサービスのメリット・デメリット2017-08-22 Python×Djangoで作るHR Techサービスのメリット・デメリット
2017-08-22 Python×Djangoで作るHR Techサービスのメリット・デメリットRyo Nagaoka
 
Herding types with Scala macros
Herding types with Scala macrosHerding types with Scala macros
Herding types with Scala macrosMarina Sigaeva
 
Groovy puzzlers по русски с Joker 2014
Groovy puzzlers по русски с Joker 2014Groovy puzzlers по русски с Joker 2014
Groovy puzzlers по русски с Joker 2014Baruch Sadogursky
 
First step of Performance Tuning
First step of Performance TuningFirst step of Performance Tuning
First step of Performance Tuningrisou
 
Swipe 2011 - iOS Gems
Swipe 2011 - iOS GemsSwipe 2011 - iOS Gems
Swipe 2011 - iOS GemsKevin O'Neill
 
A Note on Correlated Topic Models
A Note on Correlated Topic ModelsA Note on Correlated Topic Models
A Note on Correlated Topic ModelsTomonari Masada
 
Look Ma, “update DB to HTML5 using C++”, no hands! 
Look Ma, “update DB to HTML5 using C++”, no hands! Look Ma, “update DB to HTML5 using C++”, no hands! 
Look Ma, “update DB to HTML5 using C++”, no hands! aleks-f
 
Using a mobile phone as a therapist - Superweek 2018
Using a mobile phone as a therapist - Superweek 2018Using a mobile phone as a therapist - Superweek 2018
Using a mobile phone as a therapist - Superweek 2018Peter Meyer
 

Was ist angesagt? (19)

20160616技術會議
20160616技術會議20160616技術會議
20160616技術會議
 
Rデバッグあれこれ
RデバッグあれこれRデバッグあれこれ
Rデバッグあれこれ
 
Rのスコープとフレームと環境と
Rのスコープとフレームと環境とRのスコープとフレームと環境と
Rのスコープとフレームと環境と
 
CUDA First Programs: Computer Architecture CSE448 : UAA Alaska : Notes
CUDA First Programs: Computer Architecture CSE448 : UAA Alaska : NotesCUDA First Programs: Computer Architecture CSE448 : UAA Alaska : Notes
CUDA First Programs: Computer Architecture CSE448 : UAA Alaska : Notes
 
Secuencias Recursivas, Sucesiones Recursivas & Progresiones con Geogebra
Secuencias Recursivas, Sucesiones Recursivas & Progresiones con GeogebraSecuencias Recursivas, Sucesiones Recursivas & Progresiones con Geogebra
Secuencias Recursivas, Sucesiones Recursivas & Progresiones con Geogebra
 
mobl
moblmobl
mobl
 
Flexible Data Representation with Fixpoint Types
Flexible Data Representation with Fixpoint TypesFlexible Data Representation with Fixpoint Types
Flexible Data Representation with Fixpoint Types
 
2017-08-22 Python×Djangoで作るHR Techサービスのメリット・デメリット
2017-08-22 Python×Djangoで作るHR Techサービスのメリット・デメリット2017-08-22 Python×Djangoで作るHR Techサービスのメリット・デメリット
2017-08-22 Python×Djangoで作るHR Techサービスのメリット・デメリット
 
Herding types with Scala macros
Herding types with Scala macrosHerding types with Scala macros
Herding types with Scala macros
 
Groovy puzzlers по русски с Joker 2014
Groovy puzzlers по русски с Joker 2014Groovy puzzlers по русски с Joker 2014
Groovy puzzlers по русски с Joker 2014
 
Monad
MonadMonad
Monad
 
Typelevel summit
Typelevel summitTypelevel summit
Typelevel summit
 
First step of Performance Tuning
First step of Performance TuningFirst step of Performance Tuning
First step of Performance Tuning
 
Mercado iOS & Swift vs Objective-C
Mercado iOS & Swift vs Objective-CMercado iOS & Swift vs Objective-C
Mercado iOS & Swift vs Objective-C
 
Swipe 2011 - iOS Gems
Swipe 2011 - iOS GemsSwipe 2011 - iOS Gems
Swipe 2011 - iOS Gems
 
A Note on Correlated Topic Models
A Note on Correlated Topic ModelsA Note on Correlated Topic Models
A Note on Correlated Topic Models
 
Look Ma, “update DB to HTML5 using C++”, no hands! 
Look Ma, “update DB to HTML5 using C++”, no hands! Look Ma, “update DB to HTML5 using C++”, no hands! 
Look Ma, “update DB to HTML5 using C++”, no hands! 
 
Python Day1
Python Day1Python Day1
Python Day1
 
Using a mobile phone as a therapist - Superweek 2018
Using a mobile phone as a therapist - Superweek 2018Using a mobile phone as a therapist - Superweek 2018
Using a mobile phone as a therapist - Superweek 2018
 

Ähnlich wie Functional JS for everyone - 4Developers

Functional JavaScript for everyone
Functional JavaScript for everyoneFunctional JavaScript for everyone
Functional JavaScript for everyoneBartek Witczak
 
Monadologie
MonadologieMonadologie
Monadologieleague
 
Functional programming using underscorejs
Functional programming using underscorejsFunctional programming using underscorejs
Functional programming using underscorejs偉格 高
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfHiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfHiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfHiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfHiroshi Ono
 
여자개발자모임터 6주년 개발 세미나 - Scala Language
여자개발자모임터 6주년 개발 세미나 - Scala Language여자개발자모임터 6주년 개발 세미나 - Scala Language
여자개발자모임터 6주년 개발 세미나 - Scala LanguageAshal aka JOKER
 
7 Habits For a More Functional Swift
7 Habits For a More Functional Swift7 Habits For a More Functional Swift
7 Habits For a More Functional SwiftJason Larsen
 
Go ahead, make my day
Go ahead, make my dayGo ahead, make my day
Go ahead, make my dayTor Ivry
 
Christian Gill ''Functional programming for the people''
Christian Gill ''Functional programming for the people''Christian Gill ''Functional programming for the people''
Christian Gill ''Functional programming for the people''OdessaJS Conf
 
Something about Golang
Something about GolangSomething about Golang
Something about GolangAnton Arhipov
 
Functional Programming with Groovy
Functional Programming with GroovyFunctional Programming with Groovy
Functional Programming with GroovyArturo Herrero
 
関数潮流(Function Tendency)
関数潮流(Function Tendency)関数潮流(Function Tendency)
関数潮流(Function Tendency)riue
 
Gentle Introduction to Functional Programming
Gentle Introduction to Functional ProgrammingGentle Introduction to Functional Programming
Gentle Introduction to Functional ProgrammingSaurabh Singh
 
TypeScript - All you ever wanted to know - Tech Talk by Epic Labs
TypeScript - All you ever wanted to know - Tech Talk by Epic LabsTypeScript - All you ever wanted to know - Tech Talk by Epic Labs
TypeScript - All you ever wanted to know - Tech Talk by Epic LabsAlfonso Peletier
 
Scala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecScala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecLoïc Descotte
 

Ähnlich wie Functional JS for everyone - 4Developers (20)

Functional JavaScript for everyone
Functional JavaScript for everyoneFunctional JavaScript for everyone
Functional JavaScript for everyone
 
Monadologie
MonadologieMonadologie
Monadologie
 
Functional programming using underscorejs
Functional programming using underscorejsFunctional programming using underscorejs
Functional programming using underscorejs
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
 
Elm: give it a try
Elm: give it a tryElm: give it a try
Elm: give it a try
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
여자개발자모임터 6주년 개발 세미나 - Scala Language
여자개발자모임터 6주년 개발 세미나 - Scala Language여자개발자모임터 6주년 개발 세미나 - Scala Language
여자개발자모임터 6주년 개발 세미나 - Scala Language
 
7 Habits For a More Functional Swift
7 Habits For a More Functional Swift7 Habits For a More Functional Swift
7 Habits For a More Functional Swift
 
Go ahead, make my day
Go ahead, make my dayGo ahead, make my day
Go ahead, make my day
 
Scala best practices
Scala best practicesScala best practices
Scala best practices
 
Christian Gill ''Functional programming for the people''
Christian Gill ''Functional programming for the people''Christian Gill ''Functional programming for the people''
Christian Gill ''Functional programming for the people''
 
Something about Golang
Something about GolangSomething about Golang
Something about Golang
 
Functional Programming with Groovy
Functional Programming with GroovyFunctional Programming with Groovy
Functional Programming with Groovy
 
関数潮流(Function Tendency)
関数潮流(Function Tendency)関数潮流(Function Tendency)
関数潮流(Function Tendency)
 
Gentle Introduction to Functional Programming
Gentle Introduction to Functional ProgrammingGentle Introduction to Functional Programming
Gentle Introduction to Functional Programming
 
TypeScript - All you ever wanted to know - Tech Talk by Epic Labs
TypeScript - All you ever wanted to know - Tech Talk by Epic LabsTypeScript - All you ever wanted to know - Tech Talk by Epic Labs
TypeScript - All you ever wanted to know - Tech Talk by Epic Labs
 
Scala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecScala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar Prokopec
 

Kürzlich hochgeladen

2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shards2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shardsChristopher Curtin
 
Understanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM ArchitectureUnderstanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM Architecturerahul_net
 
SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?Alexandre Beguel
 
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...OnePlan Solutions
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalLionel Briand
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...OnePlan Solutions
 
eSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration toolseSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration toolsosttopstonverter
 
Not a Kubernetes fan? The state of PaaS in 2024
Not a Kubernetes fan? The state of PaaS in 2024Not a Kubernetes fan? The state of PaaS in 2024
Not a Kubernetes fan? The state of PaaS in 2024Anthony Dahanne
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxAndreas Kunz
 
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...OnePlan Solutions
 
Ronisha Informatics Private Limited Catalogue
Ronisha Informatics Private Limited CatalogueRonisha Informatics Private Limited Catalogue
Ronisha Informatics Private Limited Catalogueitservices996
 
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdfEnhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdfRTS corp
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationBradBedford3
 
Osi security architecture in network.pptx
Osi security architecture in network.pptxOsi security architecture in network.pptx
Osi security architecture in network.pptxVinzoCenzo
 
Effectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryErrorEffectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryErrorTier1 app
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfMarharyta Nedzelska
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsSafe Software
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsChristian Birchler
 
Large Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLarge Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLionel Briand
 
Strategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero resultsStrategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero resultsJean Silva
 

Kürzlich hochgeladen (20)

2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shards2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shards
 
Understanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM ArchitectureUnderstanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM Architecture
 
SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?
 
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive Goal
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
 
eSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration toolseSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration tools
 
Not a Kubernetes fan? The state of PaaS in 2024
Not a Kubernetes fan? The state of PaaS in 2024Not a Kubernetes fan? The state of PaaS in 2024
Not a Kubernetes fan? The state of PaaS in 2024
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
 
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
 
Ronisha Informatics Private Limited Catalogue
Ronisha Informatics Private Limited CatalogueRonisha Informatics Private Limited Catalogue
Ronisha Informatics Private Limited Catalogue
 
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdfEnhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion Application
 
Osi security architecture in network.pptx
Osi security architecture in network.pptxOsi security architecture in network.pptx
Osi security architecture in network.pptx
 
Effectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryErrorEffectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryError
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdf
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data Streams
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
 
Large Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLarge Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and Repair
 
Strategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero resultsStrategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero results
 

Functional JS for everyone - 4Developers

  • 2.
  • 6. function youngerThan(limit, age) { return age < limit }
  • 7. function youngerThan(limit) { return function(age) { return age < limit } }
  • 8. function youngerThan(limit) { return function(age) { return age < limit } } const youngerThanMe = youngerThan(28) ... people.map(youngerThanMe)
  • 9. In programming language design, a first-class citizen (…) is an entity which supports all the operations generally available to other entities. These operations typically include being passed as an argument, returned from a function, and assigned to a variable
  • 10. let languages = ['JavaScript', 'Scala', 'Go'] ... ... ... ... let divs = [] for(let i = 0; i < languages.length; i++) { divs.push(`<div>${langs[i]}</div>`) }
  • 11. let languages = ['JavaScript', 'Scala', 'Go'] languages.push('Java') languages.push('Ruby') languages.splice(0, 3) let divs = [] for(let i = 0; i < languages.length; i++) { divs.push(`<div>${languages[i]}</div>`) }
  • 12. const languages = Immutable.List.of( ‘JavaScript', ‘Scala', ‘Go' ) ... ... let divs = [] for(let i = 0; i < languages.length; i++) { divs.push(`<div>${languages[i]}</div>`) }
  • 13. • always evaluates to same result for the same input • evaluation does not cause any semantically observable side effects Pure function
  • 14. let user = {...} function createMessage(text) { const message = Db.save(text) return message } function sendMessage(text) { const message = createMessage(text) const messageId = MessageService.send(message, user) return messageId } IMPURE
  • 15. function createMessage(Db, text) { const message = Db.save(text) return message } function sendMessage(Db, MessageService, text, user) { const message = createMessage(Db, text) const messageId = MessageService.send(message, user) return messageId } PURE
  • 16. function createMessage(Db, text) { const message = Db.save(text) return message } function sendMessage(Db, MessageService, text, user) { const message = createMessage(Db, text) const messageId = MessageService.send(message, user) return messageId } Explicit dependency / Self-documenting
  • 17. Testable function createMessage(Db, text) { const message = Db.save(text) return message } function sendMessage(Db, MessageService, text, user) { const message = createMessage(Db, text) const messageId = MessageService.send(message, user) return messageId }
  • 18. Resonable function createMessage(Db, text) { const message = Db.save(text) return message } function sendMessage(Db, MessageService, text, user) { const message = createMessage(Db, text) const messageId = MessageService.send(message, user) return messageId }
  • 19. The problem with object-oriented languages is they’ve got all this implicit environment that they carry around with them. You wanted a banana but what you got was a gorilla holding the banana... and the entire jungle Joe Armstrong, Erlang creator
  • 21. f ( x, y ) === f ( x ) ( y )
  • 22. function add(x, y) { return x + y } add(2, 3) function curried_add (x) { return function (y) { return x + y } } curried_add(2)(3)
  • 23. const increment = curried_add(1) increment(5) peopleAge.map(increment) const add10 = curried_add(10) add10(15)
  • 24.
  • 25. export const create = (fetch) => { return { ... post: (url, data, token) => { const secureHeader = token ? { 'SECURE-TOKEN': token } : {} return Q(fetch(url, { method: 'post', headers: _.assign({ 'Accept': 'application/json', 'Content-Type': 'application/json' }, secureHeader), body: JSON.stringify(data) })) } ... } export default create(fetch)
  • 26. const token = '1jflann24kh11;2114fanakf' http.post(someURL, { user: 'Henry' }, token)
  • 27. return { ... post: (token, url, data) => { ... post(token)(url)(data) currying
  • 28. const createSecured = (http, token) => { ... post: http.post(token) ... } sercureHttp.post(someURL)({ user: 'Henry' })
  • 30. const languages = ['JavaScript', 'Scala', 'Haskell'] const divs = [] for(let i = 0; i < languages.length; i++) { divs.push(`<div>${languages[i]}</div>`) } const languages = ['JavaScript', 'Scala', 'Haskell'] const divs = languages.map(l => `<div>${l}</div>`)
  • 31. const dimensions = [100, 231, 84] const sum = 0 for(let i = 0; i < dimensions.length; i++) { sum += dimensions[i] } const dimensions = [100, 231, 84] const sum = dimensions.reduce((a, b) => a + b, 0)
  • 32. const people = [{name: 'Henry', age: 21}, ... ] const adults = [] for(let i = 0; i < people.length; i++) { if(people[i].age >= 18) { adults.push(people[i]) } } const people = [{name: 'Henry', age: 21}, ... ] const adults = people.filter(p => p.age >= 18)
  • 33.
  • 35. f(g(x)) === (f ∘ g)(x)
  • 36. function compose(f, g) { return function(x) { return f(g(x)) } }
  • 37. const add2 = (x) => x + 2 const multiplyBy2 = (x) => x * 2 multiplyBy2(add2(3)) const add2ThenMultiplyBy2 = compose(multiplyBy2, add2) add2ThenMultiplyBy2(3)
  • 38. function convertToAlbums(json) { const artist = extractArtist(json) const album = ... return album } function extractTracks(album) { const rawTracks = album.tracks const tracks = ... return tracks } function trackElem(track) { return `<li>${track.name} - ${track.duration}</li>` } const tracks = compose(extractTracks, convertToAlbums) const tracksFromJson = compose(map(trackElem), tracks) tracksFromJson(albumJson)
  • 39.
  • 41. function Burrito(x) => ({ map: f => Burrito(f(x)) })
  • 42. function Burrito(x) => ({ map: f => Burrito(f(x)) }) const food = ... Burrito(food) .map(f => return peel(f)) .map(f => return chop(f)) .map(f => return cook(f)) /////// // Burrito(cooked(chopped(peeled(food)))) ///////
  • 43. function Burrito(x) => ({ map: f => Burrito(f(x)), fold: f => f(x) }) const food = ... Burrito(food) .map(x => return peel(x)) .map(x => return chop(x)) .map(x => return cook(x)) .fold(x => return grill(x)) /////// // grilled(cooked(chopped(peeled(food)))) ///////
  • 44. Burrito we all know const hours = [ '2017-03-31T10:41:47.707Z', '2017-03-31T10:41:47.707Z', '2017-03-31T10:41:47.707Z' ] hours .map(h => moment.utc(h)) .map(m => new Date( m.year(), m.month(), m.date(), m.hour(), m.minutes() ))
  • 45. And I say MAYBE
  • 46. const find = (list, predicate) => { for (let i = 0; i < list.length; ++i) { const item = list[i] if (predicate(item)) { return item } } return null }
  • 47. const render = (text) => (`<div>That one is AWESOME ${text}!!!</div>`) const langs = ['JS', 'Haskell', 'Scala'] const js = find(langs, l => return l.length === 2) if (js !== null) { return '<div>hmm</div>' } else { render(js) } //OR const render = (text) => { if(text == null) { return '<div>hmm</div>' } else { return `<div>That one is AWESOME ${text}!!!</div>` } } const js = find(langs, l => return l === 'JS') render(js)
  • 48. const find = (list, predicate) => { for (let i = 0; i < list.length; ++i) { const item = list[i] if (predicate(item)) { return item } } return null } const find = (list, predicate) => { for (let i = 0; i < list.length; ++i) { const item = list[i] if (predicate(item)) { return Maybe.Just(item) } } return Maybe.Nothing() } and I say MAYBE
  • 49. const render = (text) => (`<div>That one is AWESOME ${text}!!!</div>`) const langs = ['JS', 'Haskell', 'Scala'] const best = find(langs, l => return l === 'JS') best .map(render) .getOrElse('<div>hmm</div>)
  • 51. const tripIds = reduce(trips, (acc, t) => { acc.push(t._id) return acc }, [])
  • 52. const tripsIds = map(trips, t => t._id) const tripsIds = map(trips, ’_id’) OR
  • 53. If you have a hammer, everything looks like a nail.
  • 55. function createTimeslots(trip) { const slots = _.reduce(trip.days, (acc, d) => { let [startHour, startMinutes] = _.map(d.startHour.split(':'), i => parseInt(i, 10)) startMinutes = normalizeStartMinutes(startMinutes) const start = ... const [endHour, endMinutes] = _.map(d.endHour.split(':'), i => parseInt(i, 10)) const end = ... /// GIVE ME MORE return acc }, []) return slots }
  • 56. function createTimeslots(trip) { ///GIVE ME MORE } function createTimeslotsFromTrips(trips) { return map(trips, createTimeslots).flatten() } function createTimeslotsFromTrips(trips) { return flatMap(trips, createTimeslots) } function createTimeslotsFromTrips(trips) { return flatMap(createTimeslots, trips) } function createTimeslotsFromTrips(trips) { return flatMap(createTimeslots)(trips) }
  • 57. const createTimeslotsFromTrips = _.flatMap(createTimeslots)
  • 58.