SlideShare ist ein Scribd-Unternehmen logo
1 von 71
Downloaden Sie, um offline zu lesen
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)

Weitere ähnliche Inhalte

Was ist angesagt?

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
 

Was ist angesagt? (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
 

Ähnlich wie 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
 

Ähnlich wie 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)
 

Kürzlich hochgeladen

Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...apidays
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbuapidays
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024The Digital Insurer
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 

Kürzlich hochgeladen (20)

Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 

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