SlideShare une entreprise Scribd logo
1  sur  71
Télécharger pour lire hors ligne
Talk Functional Javascript!
//+ CV.js :: September 18th, 2013
Kevin Welcher
Shout Out
Shout Out
Something about Camp?
10k Feet
• [Underscore.js / Lodash.js]
• Functional Concepts
• Composition
• Currying
• [Demo]
Underscore.js
Lodash.js
Highlights
• reduce
• map
• pluck
• filter
• find
reduce
• The grandaddy, most iterators can be made
out of reduce
• “Reduce a list to a new object”
map
• Bread and butter iterator
• Used to transform a list of elements from
one type to another
• Whatever is returned within the iterator is
the new object
pluck
• Iterates over a list of objects and returns a
new list made of the specified property
from each object
• A common use for map
• IE: plucking the name from an array of
people objects
filter
• Only allows values that pass a predicate
into the new list
• As with all these methods, it returns copies
of the data
find
• Accepts a predicate and returns the first
item that passes the predicate
Much, much more...
• Many predicates
(isArray, isNull, ...)
• keys / values
• groupBy
• result
• array methods
• union / intersection
• chain / compose
• extend / defaults
• simple templates
• pick / omit
FP vs OO
• The language of the... language
• How complexity is hidden
• How data is stored
Functional Concepts
Function purity
• Deterministic
• Does not depend on external state
• Does not depend on IO
• Does not cause side effects
Function purity
var View = Backbone.View.extend({
initialize: function() {
this.generateList();
},
generateList: function() {
this.list = new Backbone.Collection([
{name: 'sally'},
{name: 'joe'}
]);
}
});
Function purity
var View = Backbone.View.extend({
initialize: function() {
this.list = this.generateList();
},
generateList: function() {
return new Backbone.Collection([
{name: 'sally'},
{name: 'joe'}
]);
}
});
Functions as data
• First class citizens
• Identified by their returns
• Modifiable
Functions as building blocks
Functions which consume the return value of the
function that follows.
Composition:
Functions as building blocks
a() b() c()
a(b(c(x))) === compose(a, b, c)(x)
Composition
Functions as building blocks
function add1 (x) {
return x + 1;
}
var add3 = compose(add1, add1, add1);
add3(0);
//> 3
Functions as building blocks
function add1 (x) {
return x + 1;
}
var add3 = compose(add1, add1, add1);
add3(0);
//> 3
0
Functions as building blocks
function add1 (x) {
return x + 1;
}
var add3 = compose(add1, add1, add1);
add3(0);
//> 3
01
Functions as building blocks
function add1 (x) {
return x + 1;
}
var add3 = compose(add1, add1, add1);
add3(0);
//> 3
012
Functions as building blocks
function add1 (x) {
return x + 1;
}
var add3 = compose(add1, add1, add1);
add3(0);
//> 3
0123
Functions as building blocks
function not (x) {
return !x;
}
var boolify = compose(not, not);
not(not({}));
boolify({});
//> true
Functions as building blocks
function addTitle (x) {
return ‘Mr. ‘ + x;
}
function addSalutation (x) {
return ‘G’day, ‘ + x;
}
var meetAndGreet = compose(addSalutation, addTitle);
addSalutation(addTitle('Baggins'));
meetAndGreet('Baggins');
//> G’day, Mr. Baggins
Functions as building blocks
function add (x, y) {
return x + y;
}
var add1 = compose(???);
//> profit
Currying
“Taking a function that takes multiple arguments and
transforming it to a chain of functions that accept a single
argument.” - Wikipedia
Notation
//+ <method name> :: type -> type -> type
Notation
//+ <method name> :: type -> type -> type
A function that take takes an argument and returns a
value of type
Notation
//+ <method name> :: type -> type -> type
A function that take takes an argument and returns a
value of type
integer -> integer
A function that takes in a single
argument of type integer
The return type of integer. Since
nothing follows, it is the final return
Notation
//+ <method name> :: type -> type -> type
A function that take takes an argument and returns a
value of type
Notation
//+ <method name> :: type -> type -> type
The ultimate return value of a function
//+ not :: a -> boolean
function not (x) {
return !x;
}
not(true) //> false
//+ not :: a -> boolean
function not (x) {
return !x;
}
not(true) //> false
The a (or any other lower case letter) means we
don’t care about the type.
//+ add :: a, a -> a
function add(x, y) {
return x + y;
}
add(1, 2); //> 3
//+ add :: a, a -> a
function add(x, y) {
return x + y;
}
add(1, 2); //> 3
I am abusing notation :(
“Taking a function that takes multiple arguments and
transforming it to a chain of functions that accept a single
argument.” - Wikipedia
//+ add :: a, a -> a
//+ add :: a -> a -> a
//+ add :: a -> a -> a
function add(x) {
return function (y) {
return x + y;
};
}
add(1)(2); //> 3
ed
//+ add :: a -> a -> a
function add(x) {
return function (y) {
return x + y;
};
}
add(1)(2); //> 3
ed
//+ add :: a -> a -> a
//+ add :: 1 -> a -> a
//+ add1 :: integer -> integer
var add1 = add(1);
add1(2);
//> 3
//+ add :: a -> a -> a
//+ add :: ‘Mr. ‘ -> a -> a
//+ addTitle :: string -> string
var addTitle = add('Mr. ');
addTitle('Baggins');
//> Mr. Baggins
Problem
That _ is ugly
//+ add :: a -> a -> a
function add(x) {
return function (y) {
return x + y;
};
}
add(1)(2); //> 3
autoCurry
A custom function that automatically curries for you.
For each parameter of a function, it returns a new
function.
That _ is ugly
//+ add :: a -> a -> a
var add = function(x, y) {
return x + y;
}.autoCurry();
add(1, 2); //> 3
add(1)(2); //> 3 Awww yissss
Cool Story Bru...
Let Me ConvinceYou
With...
More Examples!
reduce
//+ reduce :: fn -> a -> array -> a
var reduce = function (fn, start, list) {
// ...
}.autoCurry();
reduce
//+ reduce :: fn -> a -> array -> a
var reduce = function (fn, start, list) {
// ...
}.autoCurry();
function (cnrt, val, index, list) {
// ...
}
Sum all the numbers in
a list?
var items = [1, 2, 3];
//+ reduce :: fn -> a -> array -> a
reduce(function (crnt, val, index, list) {
return crnt + val;
}, 0, items);
//> 6
var items = [1, 2, 3];
//+ reduce :: fn -> a -> array -> a
reduce(function (crnt, val, index, list) {
return crnt + val;
}, 0, items);
//> 6
We don’t use these two
arguments so we can omit them
var items = [1, 2, 3];
//+ reduce :: fn -> a -> array -> a
reduce(function (crnt, val) {
return crnt + val;
}, 0, items);
//> 6
var items = [1, 2, 3];
//+ reduce :: fn -> a -> array -> a
reduce(function (crnt, val) {
return crnt + val;
}, 0, items);
//> 6
This function looks familiar...
//+ add :: a -> a -> a
var add = function(x, y) {
return x + y;
}.autoCurry();
var items = [1, 2, 3];
//+ reduce :: fn -> a -> array -> a
reduce(function (x, y) {
return x + y;
}, 0, items);
//> 6
var items = [1, 2, 3];
//+ reduce :: fn -> a -> array -> a
reduce(function (x, y) {
return x + y;
}, 0, items);
//> 6
Instead of inlining the function, just pass
the function’s pointer
var items = [1, 2, 3];
//+ reduce :: fn -> a -> array -> a
reduce(add, 0, items);
//> 6
var items = [1, 2, 3];
//+ reduce :: fn -> a -> array -> a
reduce(add, 0, items);
//> 6
Cool! But isn’t reduce curried?
Can we make this into a generic function?
var items = [1, 2, 3];
//+ reduce :: add -> 0 -> array -> a
//+ sum :: array -> integer
var sum = reduce(add, 0);
sum(items);
//> 6
Demo
https://gist.github.com/kaw2k/6312261
Lessons Learned?
Keep your methods short and
to the point
It is easier to build things if your building blocks are small
Stick your data as the last
parameter
reduce = function (fn, starting value, data)
function (general, ..., specific)
Optional parameters are hard
Make a general function and curry it to take optional stuff
Functional purity is pretty cool
• Easier to maintain
• Easier to reason
• Easier to test
• Easier to transport
Obligatory Marketing
(We are hiring)

Contenu connexe

Tendances

An Intro To ES6
An Intro To ES6An Intro To ES6
An Intro To ES6FITC
 
NS2: AWK and GNUplot - PArt III
NS2: AWK and GNUplot - PArt IIINS2: AWK and GNUplot - PArt III
NS2: AWK and GNUplot - PArt IIIAjit Nayak
 
[Let'Swift 2019] 실용적인 함수형 프로그래밍 워크샵
[Let'Swift 2019] 실용적인 함수형 프로그래밍 워크샵[Let'Swift 2019] 실용적인 함수형 프로그래밍 워크샵
[Let'Swift 2019] 실용적인 함수형 프로그래밍 워크샵Wanbok Choi
 
Swift Sequences & Collections
Swift Sequences & CollectionsSwift Sequences & Collections
Swift Sequences & CollectionsCocoaHeads France
 
_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
 
Functional programming using underscorejs
Functional programming using underscorejsFunctional programming using underscorejs
Functional programming using underscorejs偉格 高
 
미려한 UI/UX를 위한 여정
미려한 UI/UX를 위한 여정미려한 UI/UX를 위한 여정
미려한 UI/UX를 위한 여정SeungChul Kang
 
Javascript essential-pattern
Javascript essential-patternJavascript essential-pattern
Javascript essential-pattern偉格 高
 
The Ring programming language version 1.10 book - Part 43 of 212
The Ring programming language version 1.10 book - Part 43 of 212The Ring programming language version 1.10 book - Part 43 of 212
The Ring programming language version 1.10 book - Part 43 of 212Mahmoud Samir Fayed
 
The Ring programming language version 1.3 book - Part 14 of 88
The Ring programming language version 1.3 book - Part 14 of 88The Ring programming language version 1.3 book - Part 14 of 88
The Ring programming language version 1.3 book - Part 14 of 88Mahmoud Samir Fayed
 
ES6 - Next Generation Javascript
ES6 - Next Generation JavascriptES6 - Next Generation Javascript
ES6 - Next Generation JavascriptRamesh Nair
 

Tendances (17)

ECMAScript 6
ECMAScript 6ECMAScript 6
ECMAScript 6
 
An Intro To ES6
An Intro To ES6An Intro To ES6
An Intro To ES6
 
NS2: AWK and GNUplot - PArt III
NS2: AWK and GNUplot - PArt IIINS2: AWK and GNUplot - PArt III
NS2: AWK and GNUplot - PArt III
 
[Let'Swift 2019] 실용적인 함수형 프로그래밍 워크샵
[Let'Swift 2019] 실용적인 함수형 프로그래밍 워크샵[Let'Swift 2019] 실용적인 함수형 프로그래밍 워크샵
[Let'Swift 2019] 실용적인 함수형 프로그래밍 워크샵
 
Swift Sequences & Collections
Swift Sequences & CollectionsSwift Sequences & Collections
Swift Sequences & Collections
 
_Function Builders in Swift #love_swift
_Function Builders in Swift #love_swift_Function Builders in Swift #love_swift
_Function Builders in Swift #love_swift
 
this
thisthis
this
 
Functional programming using underscorejs
Functional programming using underscorejsFunctional programming using underscorejs
Functional programming using underscorejs
 
미려한 UI/UX를 위한 여정
미려한 UI/UX를 위한 여정미려한 UI/UX를 위한 여정
미려한 UI/UX를 위한 여정
 
Javascript essential-pattern
Javascript essential-patternJavascript essential-pattern
Javascript essential-pattern
 
The Ring programming language version 1.10 book - Part 43 of 212
The Ring programming language version 1.10 book - Part 43 of 212The Ring programming language version 1.10 book - Part 43 of 212
The Ring programming language version 1.10 book - Part 43 of 212
 
The Ring programming language version 1.3 book - Part 14 of 88
The Ring programming language version 1.3 book - Part 14 of 88The Ring programming language version 1.3 book - Part 14 of 88
The Ring programming language version 1.3 book - Part 14 of 88
 
EcmaScript 6
EcmaScript 6 EcmaScript 6
EcmaScript 6
 
ES6 - Next Generation Javascript
ES6 - Next Generation JavascriptES6 - Next Generation Javascript
ES6 - Next Generation Javascript
 
Oop presentation
Oop presentationOop presentation
Oop presentation
 
Oop assignment 02
Oop assignment 02Oop assignment 02
Oop assignment 02
 
Tracing and awk in ns2
Tracing and awk in ns2Tracing and awk in ns2
Tracing and awk in ns2
 

Similaire à Functional Javascript, CVjs

TI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsTI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsEelco Visser
 
Why Haskell Matters
Why Haskell MattersWhy Haskell Matters
Why Haskell Mattersromanandreg
 
Столпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай МозговойСтолпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай МозговойSigma Software
 
Thinking Functionally with JavaScript
Thinking Functionally with JavaScriptThinking Functionally with JavaScript
Thinking Functionally with JavaScriptLuis Atencio
 
Intro to Javascript
Intro to JavascriptIntro to Javascript
Intro to JavascriptAnjan Banda
 
Functional programming basics
Functional programming basicsFunctional programming basics
Functional programming basicsopenbala
 
Functional Programming for OO Programmers (part 2)
Functional Programming for OO Programmers (part 2)Functional Programming for OO Programmers (part 2)
Functional Programming for OO Programmers (part 2)Calvin Cheng
 
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6Dmitry Soshnikov
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript IntroductionDmitry Sheiko
 
Bindings: the zen of montage
Bindings: the zen of montageBindings: the zen of montage
Bindings: the zen of montageKris Kowal
 
Object-Oriented Javascript
Object-Oriented JavascriptObject-Oriented Javascript
Object-Oriented Javascriptkvangork
 
Object-Oriented JavaScript
Object-Oriented JavaScriptObject-Oriented JavaScript
Object-Oriented JavaScriptkvangork
 
Functors, applicatives, monads
Functors, applicatives, monadsFunctors, applicatives, monads
Functors, applicatives, monadsrkaippully
 
Cycle.js - A functional reactive UI framework
Cycle.js - A functional reactive UI frameworkCycle.js - A functional reactive UI framework
Cycle.js - A functional reactive UI frameworkNikos Kalogridis
 
Cycle.js - Functional reactive UI framework (Nikos Kalogridis)
Cycle.js - Functional reactive UI framework (Nikos Kalogridis)Cycle.js - Functional reactive UI framework (Nikos Kalogridis)
Cycle.js - Functional reactive UI framework (Nikos Kalogridis)GreeceJS
 

Similaire à Functional Javascript, CVjs (20)

25-functions.ppt
25-functions.ppt25-functions.ppt
25-functions.ppt
 
TI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsTI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class Functions
 
Why Haskell Matters
Why Haskell MattersWhy Haskell Matters
Why Haskell Matters
 
Столпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай МозговойСтолпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай Мозговой
 
Thinking Functionally with JavaScript
Thinking Functionally with JavaScriptThinking Functionally with JavaScript
Thinking Functionally with JavaScript
 
Intro to Javascript
Intro to JavascriptIntro to Javascript
Intro to Javascript
 
Functional programming basics
Functional programming basicsFunctional programming basics
Functional programming basics
 
ES6: The Awesome Parts
ES6: The Awesome PartsES6: The Awesome Parts
ES6: The Awesome Parts
 
Functional Programming for OO Programmers (part 2)
Functional Programming for OO Programmers (part 2)Functional Programming for OO Programmers (part 2)
Functional Programming for OO Programmers (part 2)
 
Javascript
JavascriptJavascript
Javascript
 
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
 
Bindings: the zen of montage
Bindings: the zen of montageBindings: the zen of montage
Bindings: the zen of montage
 
ES6 Overview
ES6 OverviewES6 Overview
ES6 Overview
 
Object-Oriented Javascript
Object-Oriented JavascriptObject-Oriented Javascript
Object-Oriented Javascript
 
Object-Oriented JavaScript
Object-Oriented JavaScriptObject-Oriented JavaScript
Object-Oriented JavaScript
 
Advanced JavaScript
Advanced JavaScript Advanced JavaScript
Advanced JavaScript
 
Functors, applicatives, monads
Functors, applicatives, monadsFunctors, applicatives, monads
Functors, applicatives, monads
 
Cycle.js - A functional reactive UI framework
Cycle.js - A functional reactive UI frameworkCycle.js - A functional reactive UI framework
Cycle.js - A functional reactive UI framework
 
Cycle.js - Functional reactive UI framework (Nikos Kalogridis)
Cycle.js - Functional reactive UI framework (Nikos Kalogridis)Cycle.js - Functional reactive UI framework (Nikos Kalogridis)
Cycle.js - Functional reactive UI framework (Nikos Kalogridis)
 

Dernier

Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfSeasiaInfotech2
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 

Dernier (20)

Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdf
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 

Functional Javascript, CVjs

  • 1. Talk Functional Javascript! //+ CV.js :: September 18th, 2013 Kevin Welcher
  • 4. 10k Feet • [Underscore.js / Lodash.js] • Functional Concepts • Composition • Currying • [Demo]
  • 6. Highlights • reduce • map • pluck • filter • find
  • 7. reduce • The grandaddy, most iterators can be made out of reduce • “Reduce a list to a new object”
  • 8. map • Bread and butter iterator • Used to transform a list of elements from one type to another • Whatever is returned within the iterator is the new object
  • 9. pluck • Iterates over a list of objects and returns a new list made of the specified property from each object • A common use for map • IE: plucking the name from an array of people objects
  • 10. filter • Only allows values that pass a predicate into the new list • As with all these methods, it returns copies of the data
  • 11. find • Accepts a predicate and returns the first item that passes the predicate
  • 12. Much, much more... • Many predicates (isArray, isNull, ...) • keys / values • groupBy • result • array methods • union / intersection • chain / compose • extend / defaults • simple templates • pick / omit
  • 13. FP vs OO • The language of the... language • How complexity is hidden • How data is stored
  • 15. Function purity • Deterministic • Does not depend on external state • Does not depend on IO • Does not cause side effects
  • 16. Function purity var View = Backbone.View.extend({ initialize: function() { this.generateList(); }, generateList: function() { this.list = new Backbone.Collection([ {name: 'sally'}, {name: 'joe'} ]); } });
  • 17. Function purity var View = Backbone.View.extend({ initialize: function() { this.list = this.generateList(); }, generateList: function() { return new Backbone.Collection([ {name: 'sally'}, {name: 'joe'} ]); } });
  • 18. Functions as data • First class citizens • Identified by their returns • Modifiable
  • 19. Functions as building blocks Functions which consume the return value of the function that follows. Composition:
  • 20. Functions as building blocks a() b() c() a(b(c(x))) === compose(a, b, c)(x) Composition
  • 21. Functions as building blocks function add1 (x) { return x + 1; } var add3 = compose(add1, add1, add1); add3(0); //> 3
  • 22. Functions as building blocks function add1 (x) { return x + 1; } var add3 = compose(add1, add1, add1); add3(0); //> 3 0
  • 23. Functions as building blocks function add1 (x) { return x + 1; } var add3 = compose(add1, add1, add1); add3(0); //> 3 01
  • 24. Functions as building blocks function add1 (x) { return x + 1; } var add3 = compose(add1, add1, add1); add3(0); //> 3 012
  • 25. Functions as building blocks function add1 (x) { return x + 1; } var add3 = compose(add1, add1, add1); add3(0); //> 3 0123
  • 26. Functions as building blocks function not (x) { return !x; } var boolify = compose(not, not); not(not({})); boolify({}); //> true
  • 27. Functions as building blocks function addTitle (x) { return ‘Mr. ‘ + x; } function addSalutation (x) { return ‘G’day, ‘ + x; } var meetAndGreet = compose(addSalutation, addTitle); addSalutation(addTitle('Baggins')); meetAndGreet('Baggins'); //> G’day, Mr. Baggins
  • 28. Functions as building blocks function add (x, y) { return x + y; } var add1 = compose(???); //> profit
  • 29. Currying “Taking a function that takes multiple arguments and transforming it to a chain of functions that accept a single argument.” - Wikipedia
  • 30. Notation //+ <method name> :: type -> type -> type
  • 31. Notation //+ <method name> :: type -> type -> type A function that take takes an argument and returns a value of type
  • 32. Notation //+ <method name> :: type -> type -> type A function that take takes an argument and returns a value of type integer -> integer A function that takes in a single argument of type integer The return type of integer. Since nothing follows, it is the final return
  • 33. Notation //+ <method name> :: type -> type -> type A function that take takes an argument and returns a value of type
  • 34. Notation //+ <method name> :: type -> type -> type The ultimate return value of a function
  • 35. //+ not :: a -> boolean function not (x) { return !x; } not(true) //> false
  • 36. //+ not :: a -> boolean function not (x) { return !x; } not(true) //> false The a (or any other lower case letter) means we don’t care about the type.
  • 37. //+ add :: a, a -> a function add(x, y) { return x + y; } add(1, 2); //> 3
  • 38. //+ add :: a, a -> a function add(x, y) { return x + y; } add(1, 2); //> 3 I am abusing notation :(
  • 39. “Taking a function that takes multiple arguments and transforming it to a chain of functions that accept a single argument.” - Wikipedia
  • 40. //+ add :: a, a -> a //+ add :: a -> a -> a
  • 41. //+ add :: a -> a -> a function add(x) { return function (y) { return x + y; }; } add(1)(2); //> 3 ed
  • 42. //+ add :: a -> a -> a function add(x) { return function (y) { return x + y; }; } add(1)(2); //> 3 ed
  • 43. //+ add :: a -> a -> a //+ add :: 1 -> a -> a //+ add1 :: integer -> integer var add1 = add(1); add1(2); //> 3
  • 44. //+ add :: a -> a -> a //+ add :: ‘Mr. ‘ -> a -> a //+ addTitle :: string -> string var addTitle = add('Mr. '); addTitle('Baggins'); //> Mr. Baggins
  • 46. That _ is ugly //+ add :: a -> a -> a function add(x) { return function (y) { return x + y; }; } add(1)(2); //> 3
  • 47. autoCurry A custom function that automatically curries for you. For each parameter of a function, it returns a new function.
  • 48. That _ is ugly //+ add :: a -> a -> a var add = function(x, y) { return x + y; }.autoCurry(); add(1, 2); //> 3 add(1)(2); //> 3 Awww yissss
  • 52. reduce //+ reduce :: fn -> a -> array -> a var reduce = function (fn, start, list) { // ... }.autoCurry();
  • 53. reduce //+ reduce :: fn -> a -> array -> a var reduce = function (fn, start, list) { // ... }.autoCurry(); function (cnrt, val, index, list) { // ... }
  • 54. Sum all the numbers in a list?
  • 55. var items = [1, 2, 3]; //+ reduce :: fn -> a -> array -> a reduce(function (crnt, val, index, list) { return crnt + val; }, 0, items); //> 6
  • 56. var items = [1, 2, 3]; //+ reduce :: fn -> a -> array -> a reduce(function (crnt, val, index, list) { return crnt + val; }, 0, items); //> 6 We don’t use these two arguments so we can omit them
  • 57. var items = [1, 2, 3]; //+ reduce :: fn -> a -> array -> a reduce(function (crnt, val) { return crnt + val; }, 0, items); //> 6
  • 58. var items = [1, 2, 3]; //+ reduce :: fn -> a -> array -> a reduce(function (crnt, val) { return crnt + val; }, 0, items); //> 6 This function looks familiar...
  • 59. //+ add :: a -> a -> a var add = function(x, y) { return x + y; }.autoCurry();
  • 60. var items = [1, 2, 3]; //+ reduce :: fn -> a -> array -> a reduce(function (x, y) { return x + y; }, 0, items); //> 6
  • 61. var items = [1, 2, 3]; //+ reduce :: fn -> a -> array -> a reduce(function (x, y) { return x + y; }, 0, items); //> 6 Instead of inlining the function, just pass the function’s pointer
  • 62. var items = [1, 2, 3]; //+ reduce :: fn -> a -> array -> a reduce(add, 0, items); //> 6
  • 63. var items = [1, 2, 3]; //+ reduce :: fn -> a -> array -> a reduce(add, 0, items); //> 6 Cool! But isn’t reduce curried? Can we make this into a generic function?
  • 64. var items = [1, 2, 3]; //+ reduce :: add -> 0 -> array -> a //+ sum :: array -> integer var sum = reduce(add, 0); sum(items); //> 6
  • 67. Keep your methods short and to the point It is easier to build things if your building blocks are small
  • 68. Stick your data as the last parameter reduce = function (fn, starting value, data) function (general, ..., specific)
  • 69. Optional parameters are hard Make a general function and curry it to take optional stuff
  • 70. Functional purity is pretty cool • Easier to maintain • Easier to reason • Easier to test • Easier to transport