SlideShare a Scribd company logo
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

More Related Content

What's hot

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 : Notes
Subhajit 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 Geogebra
Jose Perez
 
mobl
moblmobl
Flexible Data Representation with Fixpoint Types
Flexible Data Representation with Fixpoint TypesFlexible Data Representation with Fixpoint Types
Flexible Data Representation with Fixpoint Types
Dave 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 macros
Marina Sigaeva
 
Groovy puzzlers по русски с Joker 2014
Groovy puzzlers по русски с Joker 2014Groovy puzzlers по русски с Joker 2014
Groovy puzzlers по русски с Joker 2014
Baruch Sadogursky
 
Monad
MonadMonad
Typelevel summit
Typelevel summitTypelevel summit
Typelevel summit
Marina Sigaeva
 
First step of Performance Tuning
First step of Performance TuningFirst step of Performance Tuning
First step of Performance Tuning
risou
 
Mercado iOS & Swift vs Objective-C
Mercado iOS & Swift vs Objective-CMercado iOS & Swift vs Objective-C
Mercado iOS & Swift vs Objective-C
Mauricio Tremea Zaquia
 
Swipe 2011 - iOS Gems
Swipe 2011 - iOS GemsSwipe 2011 - iOS Gems
Swipe 2011 - iOS Gems
Kevin O'Neill
 
A Note on Correlated Topic Models
A Note on Correlated Topic ModelsA Note on Correlated Topic Models
A Note on Correlated Topic Models
Tomonari 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
 
Python Day1
Python Day1Python Day1
Python Day1
Mantavya Gajjar
 
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
Peter Meyer
 

What's hot (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
 

Similar to Functional JS for everyone - 4Developers

Functional JavaScript for everyone
Functional JavaScript for everyoneFunctional JavaScript for everyone
Functional JavaScript for everyone
Bartek Witczak
 
Monadologie
MonadologieMonadologie
Monadologie
league
 
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
Hiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
Hiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
Hiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
Hiroshi Ono
 
Elm: give it a try
Elm: give it a tryElm: give it a try
Elm: give it a try
Eugene Zharkov
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
Aleksandar Prokopec
 
여자개발자모임터 6주년 개발 세미나 - Scala Language
여자개발자모임터 6주년 개발 세미나 - Scala Language여자개발자모임터 6주년 개발 세미나 - Scala Language
여자개발자모임터 6주년 개발 세미나 - Scala Language
Ashal 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 Swift
Jason Larsen
 
Go ahead, make my day
Go ahead, make my dayGo ahead, make my day
Go ahead, make my day
Tor Ivry
 
Scala best practices
Scala best practicesScala best practices
Scala best practices
Alexander Zaidel
 
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 Golang
Anton Arhipov
 
Functional Programming with Groovy
Functional Programming with GroovyFunctional Programming with Groovy
Functional Programming with Groovy
Arturo 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 Programming
Saurabh 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 Labs
Alfonso Peletier
 
Scala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecScala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar Prokopec
Loïc Descotte
 

Similar to 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
 

Recently uploaded

Quarter 3 SLRP grade 9.. gshajsbhhaheabh
Quarter 3 SLRP grade 9.. gshajsbhhaheabhQuarter 3 SLRP grade 9.. gshajsbhhaheabh
Quarter 3 SLRP grade 9.. gshajsbhhaheabh
aisafed42
 
如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样
如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样
如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样
gapen1
 
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSISDECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
Tier1 app
 
GreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-JurisicGreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-Jurisic
Green Software Development
 
ppt on the brain chip neuralink.pptx
ppt  on   the brain  chip neuralink.pptxppt  on   the brain  chip neuralink.pptx
ppt on the brain chip neuralink.pptx
Reetu63
 
UI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
UI5con 2024 - Keynote: Latest News about UI5 and it’s EcosystemUI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
UI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
Peter Muessig
 
Oracle Database 19c New Features for DBAs and Developers.pptx
Oracle Database 19c New Features for DBAs and Developers.pptxOracle Database 19c New Features for DBAs and Developers.pptx
Oracle Database 19c New Features for DBAs and Developers.pptx
Remote DBA Services
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
Drona Infotech
 
Project Management: The Role of Project Dashboards.pdf
Project Management: The Role of Project Dashboards.pdfProject Management: The Role of Project Dashboards.pdf
Project Management: The Role of Project Dashboards.pdf
Karya Keeper
 
Enhanced Screen Flows UI/UX using SLDS with Tom Kitt
Enhanced Screen Flows UI/UX using SLDS with Tom KittEnhanced Screen Flows UI/UX using SLDS with Tom Kitt
Enhanced Screen Flows UI/UX using SLDS with Tom Kitt
Peter Caitens
 
Enums On Steroids - let's look at sealed classes !
Enums On Steroids - let's look at sealed classes !Enums On Steroids - let's look at sealed classes !
Enums On Steroids - let's look at sealed classes !
Marcin Chrost
 
Oracle 23c New Features For DBAs and Developers.pptx
Oracle 23c New Features For DBAs and Developers.pptxOracle 23c New Features For DBAs and Developers.pptx
Oracle 23c New Features For DBAs and Developers.pptx
Remote DBA Services
 
How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?
ToXSL Technologies
 
WWDC 2024 Keynote Review: For CocoaCoders Austin
WWDC 2024 Keynote Review: For CocoaCoders AustinWWDC 2024 Keynote Review: For CocoaCoders Austin
WWDC 2024 Keynote Review: For CocoaCoders Austin
Patrick Weigel
 
Modelling Up - DDDEurope 2024 - Amsterdam
Modelling Up - DDDEurope 2024 - AmsterdamModelling Up - DDDEurope 2024 - Amsterdam
Modelling Up - DDDEurope 2024 - Amsterdam
Alberto Brandolini
 
UI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
UI5con 2024 - Boost Your Development Experience with UI5 Tooling ExtensionsUI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
UI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
Peter Muessig
 
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdf
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdfTop Benefits of Using Salesforce Healthcare CRM for Patient Management.pdf
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdf
VALiNTRY360
 
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
kalichargn70th171
 
Webinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for EmbeddedWebinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for Embedded
ICS
 
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdfBaha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
Baha Majid
 

Recently uploaded (20)

Quarter 3 SLRP grade 9.. gshajsbhhaheabh
Quarter 3 SLRP grade 9.. gshajsbhhaheabhQuarter 3 SLRP grade 9.. gshajsbhhaheabh
Quarter 3 SLRP grade 9.. gshajsbhhaheabh
 
如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样
如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样
如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样
 
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSISDECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
 
GreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-JurisicGreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-Jurisic
 
ppt on the brain chip neuralink.pptx
ppt  on   the brain  chip neuralink.pptxppt  on   the brain  chip neuralink.pptx
ppt on the brain chip neuralink.pptx
 
UI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
UI5con 2024 - Keynote: Latest News about UI5 and it’s EcosystemUI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
UI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
 
Oracle Database 19c New Features for DBAs and Developers.pptx
Oracle Database 19c New Features for DBAs and Developers.pptxOracle Database 19c New Features for DBAs and Developers.pptx
Oracle Database 19c New Features for DBAs and Developers.pptx
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
 
Project Management: The Role of Project Dashboards.pdf
Project Management: The Role of Project Dashboards.pdfProject Management: The Role of Project Dashboards.pdf
Project Management: The Role of Project Dashboards.pdf
 
Enhanced Screen Flows UI/UX using SLDS with Tom Kitt
Enhanced Screen Flows UI/UX using SLDS with Tom KittEnhanced Screen Flows UI/UX using SLDS with Tom Kitt
Enhanced Screen Flows UI/UX using SLDS with Tom Kitt
 
Enums On Steroids - let's look at sealed classes !
Enums On Steroids - let's look at sealed classes !Enums On Steroids - let's look at sealed classes !
Enums On Steroids - let's look at sealed classes !
 
Oracle 23c New Features For DBAs and Developers.pptx
Oracle 23c New Features For DBAs and Developers.pptxOracle 23c New Features For DBAs and Developers.pptx
Oracle 23c New Features For DBAs and Developers.pptx
 
How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?
 
WWDC 2024 Keynote Review: For CocoaCoders Austin
WWDC 2024 Keynote Review: For CocoaCoders AustinWWDC 2024 Keynote Review: For CocoaCoders Austin
WWDC 2024 Keynote Review: For CocoaCoders Austin
 
Modelling Up - DDDEurope 2024 - Amsterdam
Modelling Up - DDDEurope 2024 - AmsterdamModelling Up - DDDEurope 2024 - Amsterdam
Modelling Up - DDDEurope 2024 - Amsterdam
 
UI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
UI5con 2024 - Boost Your Development Experience with UI5 Tooling ExtensionsUI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
UI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
 
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdf
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdfTop Benefits of Using Salesforce Healthcare CRM for Patient Management.pdf
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdf
 
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
 
Webinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for EmbeddedWebinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for Embedded
 
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdfBaha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
 

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.