SlideShare a Scribd company logo
1 of 41
Download to read offline
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(age, limit) {
return age < limit
}
function youngerThan(age) {
return function(limit) {
return age < limit
}
}
function youngerThan(age) {
return function(limit) {
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)
Bartek Witczak
@bartekwitczak
bartek@dayone.pl

More Related Content

What's hot

20180721 code defragment
20180721 code defragment20180721 code defragment
20180721 code defragmentChiwon Song
 
Develop your next app with kotlin @ AndroidMakersFr 2017
Develop your next app with kotlin @ AndroidMakersFr 2017Develop your next app with kotlin @ AndroidMakersFr 2017
Develop your next app with kotlin @ AndroidMakersFr 2017Arnaud Giuliani
 
Gearman, from the worker's perspective
Gearman, from the worker's perspectiveGearman, from the worker's perspective
Gearman, from the worker's perspectiveBrian Aker
 
Gearmam, from the_worker's_perspective copy
Gearmam, from the_worker's_perspective copyGearmam, from the_worker's_perspective copy
Gearmam, from the_worker's_perspective copyBrian Aker
 
Developer Experience i TypeScript. Najbardziej ikoniczne duo
Developer Experience i TypeScript. Najbardziej ikoniczne duoDeveloper Experience i TypeScript. Najbardziej ikoniczne duo
Developer Experience i TypeScript. Najbardziej ikoniczne duoThe Software House
 
20181020 advanced higher-order function
20181020 advanced higher-order function20181020 advanced higher-order function
20181020 advanced higher-order functionChiwon Song
 
夜子まま塾講義3(androidで電卓アプリを作る)
夜子まま塾講義3(androidで電卓アプリを作る)夜子まま塾講義3(androidで電卓アプリを作る)
夜子まま塾講義3(androidで電卓アプリを作る)Masafumi Terazono
 
Numerical Method Assignment
Numerical Method AssignmentNumerical Method Assignment
Numerical Method Assignmentashikul akash
 
Promise: async programming hero
Promise: async programming heroPromise: async programming hero
Promise: async programming heroThe Software House
 
[JuraSIC! Meetup] Mateusz Stasch - Monady w .NET
[JuraSIC! Meetup] Mateusz Stasch - Monady w .NET[JuraSIC! Meetup] Mateusz Stasch - Monady w .NET
[JuraSIC! Meetup] Mateusz Stasch - Monady w .NETFuture Processing
 
_Function Builders in Swift #love_swift
_Function Builders in Swift #love_swift_Function Builders in Swift #love_swift
_Function Builders in Swift #love_swiftTomohiro Kumagai
 
Let the type system be your friend
Let the type system be your friendLet the type system be your friend
Let the type system be your friendThe Software House
 

What's hot (20)

20180721 code defragment
20180721 code defragment20180721 code defragment
20180721 code defragment
 
Container adapters
Container adaptersContainer adapters
Container adapters
 
Develop your next app with kotlin @ AndroidMakersFr 2017
Develop your next app with kotlin @ AndroidMakersFr 2017Develop your next app with kotlin @ AndroidMakersFr 2017
Develop your next app with kotlin @ AndroidMakersFr 2017
 
Gearman, from the worker's perspective
Gearman, from the worker's perspectiveGearman, from the worker's perspective
Gearman, from the worker's perspective
 
Gearmam, from the_worker's_perspective copy
Gearmam, from the_worker's_perspective copyGearmam, from the_worker's_perspective copy
Gearmam, from the_worker's_perspective copy
 
Lambda expressions in C++
Lambda expressions in C++Lambda expressions in C++
Lambda expressions in C++
 
Developer Experience i TypeScript. Najbardziej ikoniczne duo
Developer Experience i TypeScript. Najbardziej ikoniczne duoDeveloper Experience i TypeScript. Najbardziej ikoniczne duo
Developer Experience i TypeScript. Najbardziej ikoniczne duo
 
20181020 advanced higher-order function
20181020 advanced higher-order function20181020 advanced higher-order function
20181020 advanced higher-order function
 
夜子まま塾講義3(androidで電卓アプリを作る)
夜子まま塾講義3(androidで電卓アプリを作る)夜子まま塾講義3(androidで電卓アプリを作る)
夜子まま塾講義3(androidで電卓アプリを作る)
 
Numerical Method Assignment
Numerical Method AssignmentNumerical Method Assignment
Numerical Method Assignment
 
Sneaking inside Kotlin features
Sneaking inside Kotlin featuresSneaking inside Kotlin features
Sneaking inside Kotlin features
 
Promise: async programming hero
Promise: async programming heroPromise: async programming hero
Promise: async programming hero
 
[JuraSIC! Meetup] Mateusz Stasch - Monady w .NET
[JuraSIC! Meetup] Mateusz Stasch - Monady w .NET[JuraSIC! Meetup] Mateusz Stasch - Monady w .NET
[JuraSIC! Meetup] Mateusz Stasch - Monady w .NET
 
Python GC
Python GCPython GC
Python GC
 
_Function Builders in Swift #love_swift
_Function Builders in Swift #love_swift_Function Builders in Swift #love_swift
_Function Builders in Swift #love_swift
 
Let the type system be your friend
Let the type system be your friendLet the type system be your friend
Let the type system be your friend
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 
Introduction to kotlin
Introduction to kotlinIntroduction to kotlin
Introduction to kotlin
 
.net progrmming part2
.net progrmming part2.net progrmming part2
.net progrmming part2
 
C++ TUTORIAL 10
C++ TUTORIAL 10C++ TUTORIAL 10
C++ TUTORIAL 10
 

Similar to Functional JavaScript for everyone

Pick up the low-hanging concurrency fruit
Pick up the low-hanging concurrency fruitPick up the low-hanging concurrency fruit
Pick up the low-hanging concurrency fruitVaclav Pech
 
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
 
オープンデータを使ったモバイルアプリ開発(応用編)
オープンデータを使ったモバイルアプリ開発(応用編)オープンデータを使ったモバイルアプリ開発(応用編)
オープンデータを使ったモバイルアプリ開発(応用編)Takayuki Goto
 
Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Jonas Bonér
 
Pragmatic Real-World Scala
Pragmatic Real-World ScalaPragmatic Real-World Scala
Pragmatic Real-World Scalaparag978978
 
Scala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecScala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecLoïc Descotte
 
Intro to Javascript
Intro to JavascriptIntro to Javascript
Intro to JavascriptAnjan Banda
 
4Developers: Michał Szczepanik- Kotlin - Let’s ketchup it
4Developers: Michał Szczepanik- Kotlin - Let’s ketchup it4Developers: Michał Szczepanik- Kotlin - Let’s ketchup it
4Developers: Michał Szczepanik- Kotlin - Let’s ketchup itPROIDEA
 
JavaScript - Agora nervoso
JavaScript - Agora nervosoJavaScript - Agora nervoso
JavaScript - Agora nervosoLuis Vendrame
 
Building android apps with kotlin
Building android apps with kotlinBuilding android apps with kotlin
Building android apps with kotlinShem Magnezi
 
여자개발자모임터 6주년 개발 세미나 - Scala Language
여자개발자모임터 6주년 개발 세미나 - Scala Language여자개발자모임터 6주년 개발 세미나 - Scala Language
여자개발자모임터 6주년 개발 세미나 - Scala LanguageAshal aka JOKER
 
What's in Kotlin for us - Alexandre Greschon, MyHeritage
What's in Kotlin for us - Alexandre Greschon, MyHeritageWhat's in Kotlin for us - Alexandre Greschon, MyHeritage
What's in Kotlin for us - Alexandre Greschon, MyHeritageDroidConTLV
 
Go Says WAT?
Go Says WAT?Go Says WAT?
Go Says WAT?jonbodner
 
Category theory, Monads, and Duality in the world of (BIG) Data
Category theory, Monads, and Duality in the world of (BIG) DataCategory theory, Monads, and Duality in the world of (BIG) Data
Category theory, Monads, and Duality in the world of (BIG) Datagreenwop
 

Similar to Functional JavaScript for everyone (20)

Pick up the low-hanging concurrency fruit
Pick up the low-hanging concurrency fruitPick up the low-hanging concurrency fruit
Pick up the low-hanging concurrency fruit
 
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
 
オープンデータを使ったモバイルアプリ開発(応用編)
オープンデータを使ったモバイルアプリ開発(応用編)オープンデータを使ったモバイルアプリ開発(応用編)
オープンデータを使ったモバイルアプリ開発(応用編)
 
Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)
 
Pragmatic Real-World Scala
Pragmatic Real-World ScalaPragmatic Real-World Scala
Pragmatic Real-World Scala
 
Scala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecScala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar Prokopec
 
Intro to Javascript
Intro to JavascriptIntro to Javascript
Intro to Javascript
 
ProgrammingwithGOLang
ProgrammingwithGOLangProgrammingwithGOLang
ProgrammingwithGOLang
 
4Developers: Michał Szczepanik- Kotlin - Let’s ketchup it
4Developers: Michał Szczepanik- Kotlin - Let’s ketchup it4Developers: Michał Szczepanik- Kotlin - Let’s ketchup it
4Developers: Michał Szczepanik- Kotlin - Let’s ketchup it
 
mobl
moblmobl
mobl
 
Poly-paradigm Java
Poly-paradigm JavaPoly-paradigm Java
Poly-paradigm Java
 
JavaScript - Agora nervoso
JavaScript - Agora nervosoJavaScript - Agora nervoso
JavaScript - Agora nervoso
 
Building android apps with kotlin
Building android apps with kotlinBuilding android apps with kotlin
Building android apps with kotlin
 
Blocks+gcd入門
Blocks+gcd入門Blocks+gcd入門
Blocks+gcd入門
 
여자개발자모임터 6주년 개발 세미나 - Scala Language
여자개발자모임터 6주년 개발 세미나 - Scala Language여자개발자모임터 6주년 개발 세미나 - Scala Language
여자개발자모임터 6주년 개발 세미나 - Scala Language
 
What's in Kotlin for us - Alexandre Greschon, MyHeritage
What's in Kotlin for us - Alexandre Greschon, MyHeritageWhat's in Kotlin for us - Alexandre Greschon, MyHeritage
What's in Kotlin for us - Alexandre Greschon, MyHeritage
 
Go Says WAT?
Go Says WAT?Go Says WAT?
Go Says WAT?
 
ES6(ES2015) is beautiful
ES6(ES2015) is beautifulES6(ES2015) is beautiful
ES6(ES2015) is beautiful
 
Category theory, Monads, and Duality in the world of (BIG) Data
Category theory, Monads, and Duality in the world of (BIG) DataCategory theory, Monads, and Duality in the world of (BIG) Data
Category theory, Monads, and Duality in the world of (BIG) Data
 
A More Flash Like Web?
A More Flash Like Web?A More Flash Like Web?
A More Flash Like Web?
 

Recently uploaded

GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Mater
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)jennyeacort
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfFerryKemperman
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odishasmiwainfosol
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfStefano Stabellini
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Angel Borroy López
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprisepreethippts
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdfInnovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdfYashikaSharma391629
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceBrainSell Technologies
 
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
 
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
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringHironori Washizaki
 
How To Manage Restaurant Staff -BTRESTRO
How To Manage Restaurant Staff -BTRESTROHow To Manage Restaurant Staff -BTRESTRO
How To Manage Restaurant Staff -BTRESTROmotivationalword821
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Matt Ray
 
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
 

Recently uploaded (20)

GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdf
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdf
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprise
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdfInnovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdf
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. Salesforce
 
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
 
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
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their Engineering
 
How To Manage Restaurant Staff -BTRESTRO
How To Manage Restaurant Staff -BTRESTROHow To Manage Restaurant Staff -BTRESTRO
How To Manage Restaurant Staff -BTRESTRO
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
 
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
 

Functional JavaScript for everyone

  • 2.
  • 6. function youngerThan(age, limit) { return age < limit }
  • 7. function youngerThan(age) { return function(limit) { return age < limit } }
  • 8. function youngerThan(age) { return function(limit) { 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.
  • 40.