SlideShare a Scribd company logo
Maybe Functor
in Javascript
Another approach to
null handling
1
2
Origin of Null Pointer Exception
● Sir Tony Hoare was designing type systems for the
language ALGOL W and he put “Null Pointer Exception” as
part of the language, because “because it was so easy to
implement”
● In 2009, he called it “The Billion Dollar Mistake”
3
What we want:
getCountry('vn').getCity('HCMC').population;
What we have to do
var country = getCountry('vn');
if (country !== null) {
var city = country.getCity('HCMC');
if (city !== null) {
var population = city.population;
}
}
How do we fight NULL?
4
Drawbacks:
● Looks complicated
● Error-prone, especially
when there are many
nesting ifs
● Tedious to write
● Declares a lot of useless
variables
● A Functor is a container of a value
Introduction to Functor
5
A value A container of value
● A simple Functor can be implemented through an ES6 class
class Functor {
constructor(value) {
this.value = value;
}
}
One important thing about Functor
6
By definition, a functor needs to implement a
map function
Remember Array Map?
7
Let’s look at Array’s map function.
var addOne = (x) => x + 1;
var square = (x) => x * x;
var result = [1, 2, 3]
.map(addOne) // [2, 3, 4]
.map(square); // [4, 9, 16]
Implement map for Functor
8
class Functor {
constructor(value) {
this.value = value;
}
map(fn) {
var newValue = fn(this.value);
return new Functor(newValue);
}
}
Let’s see it in action (1)
9
var addOne = (x) => x + 1;
var functorOf6 = new Functor(5).map(addOne); // Functor(6)
It can also work with any value, for example, an object:
var toUpperCase = (str) => str.toUpperCase();
var exciting = (someName) => someName + ’!!!!!!!’;
var value = { name: 'grokking' };
var containerOfValue = new Functor(value)
.map(thing => thing.name) // Functor(‘grokking’)
.map(toUpperCase) // Functor(‘GROKKING’)
.map(exciting); // Functor(‘GROKKING!!!!!!!’)
Let’s see it in action (2)
10
Notice that our actual value is still inside the Functor.
var functorOf36 = new Functor(5)
.map(addOne) // Functor(6)
.map(square); // Functor(36)
var result = functorOf36 + 100; // Functor(36) + 100 ???????
How to get the value inside Functor
11
Let’s add another method to Functor to extract the value.
class Functor {
get() { return this.value; }
}
var valueInside = new Functor(5)
.map(addOne) // Functor(6)
.map(square); // Functor(36)
.get(); // 36
var toUpperCase = (str) => str.toUpperCase();
var exciting = (someName) => someName + '!!!!!!';
var valueInside = new Functor({ name: 'grokking' })
.map(people => people.name) // Functor(‘grokking’)
.map(toUpperCase) // Functor(‘GROKKING’)
.map(exciting); // Functor(‘GROKKING!!!!!!!’)
.get(); // 'GROKKING!!!!!!!'
Now we can get the value inside Functor
12
class Functor {
constructor(value) {
this.value = value;
}
map(fn) {
var newValue = fn(this.value);
return new Maybe(newValue);
}
get() {
return this.value;
}
}
Full implementation of Functor
13
var addOne = (x) => null; // we return Null
var square = (x) => x * x;
var valueInside = new Functor(1)
.map(addOne) // Functor(null)
.map(square); // Functor(null * null) ????
.get(); // ????
But we are still affected by NULL
14
The solution is to turn our functor into a Maybe
● Maybe is a kind of Functor that is Null-
friendly. Real magic happens in the map
function
● Maybe that contains a real value (not null)
is usually called a Just / Some
● Maybe that contains null value is usually
called a Nothing / None
Introduction to Maybe
15
Maybe(value) = Just(value)
Maybe(null) = Nothing
class Maybe {
constructor(value) { this.value = value; }
map(fn) {
if (this.value !== null) { // Magic happens here
var newValue = fn(this.value);
return new Maybe(newValue);
}
return new Maybe(null);
}
getOrElse(fallBackValue) {
return (this.value === null) ? this.value : fallBackValue;
}
}
Let’s implement Maybe
16
It’s pretty much the same as Functor’s example. The only difference is that we use
getOrElse instead of get
var addOne = (x) => x + 1;
var square = (x) => x * x;
var result = new Maybe(3)
.map(addOne) // Maybe(4)
.map(square) // Maybe(16)
.getOrElse(0); // 16
Maybe in action
17
When Maybe contains NULL, it will not map anymore
var result = new Maybe(3)
.map(x => null) // Maybe(null)
.map(x => x * x) // Maybe(null)
.getOrElse(0); // 0
var result = new Maybe(3)
.map(x => x + 1) // Maybe(4)
.map(x => null) // Maybe(null)
.getOrElse(0); // 0
When Null happens
18
Some real world examples
var family = {
grandma: {
mother: {
you: 'YOUR NAME HERE'
}
}
};
var you = new Maybe(family.grandma)
.map(grandma => grandma.mother)
.map(mother => mother.you)
.getOrElse('DEFAULT NAME');
// returns “YOUR NAME HERE”
var family = {
grandma: null
};
var you = new Maybe(family.grandma)
.map(grandma => grandma.mother)
.map(mother => mother.you)
.getOrElse('DEFAULT NAME');
// returns “DEFAULT NAME”
19
We can use it to safely access nested objects
Compare with what we used to do
20
var you = family.grandma.mother.you || 'DEFAULT NAME';
var you = 'DEFAULT NAME';
if (family.grandma &&
family.grandma.mother &&
family.grandma.mother.you)
{
you = family.grandma.mother.you;
}
var you = new Maybe(family.grandma)
.map(grandma => grandma.mother)
.map(mother => mother.you)
.getOrElse('DEFAULT NAME');
Short, but unsafe
Safe, but long and
nested
Safe and flattened
var population = new Maybe(getCountry('vn'))
.map(country => country.getCity('HCMC'))
.map(city => city.population)
.getOrElse(0);
Some real world examples
var country = getCountry('vn');
if (country !== null) {
var city = country.getCity('HCMC');
if (city !== null) {
var population = city.population;
}
}
21
We can rewrite our example earlier
Into shorter and flattened code
● Is just a container of value
● Is a fundamental concept in
Functional Programming. From
there you can explore Applicative
and Monad
● Is a kind of functor that checks null on each map
● Helps flatten your code
● Is used widely in many other languages:
- Haskell, Elm: Maybe
Recap
22
Maybe
Functor
References
● https://github.com/fantasyland/fantasy-land Fantasy Land Specification
● https://cwmyers.github.io/monet.js/ Powerful abstractions for Javascript
● http://adit.io/posts/2013-04-17-functors,_applicatives,_and_monads_in_pictures.html
Functor, Applicatives, Monads in pictures
● https://en.wikipedia.org/wiki/Functor (looks scary with all the math)
● http://www.mokacoding.com/blog/functor-applicative-monads-in-pictures/ (Maybe in
Swift)
● http://www.oracle.com/technetwork/articles/java/java8-optional-2175753.html Java 8
Optional
23

More Related Content

What's hot

DS- Stack ADT
DS- Stack ADTDS- Stack ADT
DS- Stack ADT
MythiliMurugan3
 
The Ring programming language version 1.6 book - Part 84 of 189
The Ring programming language version 1.6 book - Part 84 of 189The Ring programming language version 1.6 book - Part 84 of 189
The Ring programming language version 1.6 book - Part 84 of 189
Mahmoud Samir Fayed
 
Git avançado
Git avançadoGit avançado
Git avançado
Jean Carlo Machado
 
Functional php
Functional phpFunctional php
Functional php
Jean Carlo Machado
 
Golang勉強会
Golang勉強会Golang勉強会
Golang勉強会
Shin Sekaryo
 
6 new ES6 features
6 new ES6 features6 new ES6 features
6 new ES6 featuresKyle Dorman
 
Functional Programming: An Introduction
Functional Programming: An IntroductionFunctional Programming: An Introduction
Functional Programming: An Introduction
drewolson
 
Recognize Godzilla
Recognize GodzillaRecognize Godzilla
Recognize Godzilla
隊長 アイパー
 
Cpp tutorial
Cpp tutorialCpp tutorial
Cpp tutorial
Vikas Sharma
 
Circular linked list
Circular linked listCircular linked list
Circular linked list
Sayantan Sur
 
Single linked list
Single linked listSingle linked list
Single linked list
Sayantan Sur
 
Stack using Array
Stack using ArrayStack using Array
Stack using Array
Sayantan Sur
 
Debug like a doctor
Debug like a doctorDebug like a doctor
Debug like a doctor
Ouadie LAHDIOUI
 

What's hot (15)

DS- Stack ADT
DS- Stack ADTDS- Stack ADT
DS- Stack ADT
 
The Ring programming language version 1.6 book - Part 84 of 189
The Ring programming language version 1.6 book - Part 84 of 189The Ring programming language version 1.6 book - Part 84 of 189
The Ring programming language version 1.6 book - Part 84 of 189
 
week-15x
week-15xweek-15x
week-15x
 
Git avançado
Git avançadoGit avançado
Git avançado
 
Functional php
Functional phpFunctional php
Functional php
 
Golang勉強会
Golang勉強会Golang勉強会
Golang勉強会
 
6 new ES6 features
6 new ES6 features6 new ES6 features
6 new ES6 features
 
Functional Programming: An Introduction
Functional Programming: An IntroductionFunctional Programming: An Introduction
Functional Programming: An Introduction
 
Recognize Godzilla
Recognize GodzillaRecognize Godzilla
Recognize Godzilla
 
C++ programs
C++ programsC++ programs
C++ programs
 
Cpp tutorial
Cpp tutorialCpp tutorial
Cpp tutorial
 
Circular linked list
Circular linked listCircular linked list
Circular linked list
 
Single linked list
Single linked listSingle linked list
Single linked list
 
Stack using Array
Stack using ArrayStack using Array
Stack using Array
 
Debug like a doctor
Debug like a doctorDebug like a doctor
Debug like a doctor
 

Viewers also liked

Grokking TechTalk #16: F**k bad CSS
Grokking TechTalk #16: F**k bad CSSGrokking TechTalk #16: F**k bad CSS
Grokking TechTalk #16: F**k bad CSS
Grokking VN
 
Grokking TechTalk #16: React stack at lozi
Grokking TechTalk #16: React stack at loziGrokking TechTalk #16: React stack at lozi
Grokking TechTalk #16: React stack at lozi
Grokking VN
 
Grokking TechTalk #16: Html js and three way binding
Grokking TechTalk #16: Html js and three way bindingGrokking TechTalk #16: Html js and three way binding
Grokking TechTalk #16: Html js and three way binding
Grokking VN
 
Expressing your UI in JSON – plain, data binding, advanced data binding
Expressing your UI in JSON – plain, data binding, advanced data bindingExpressing your UI in JSON – plain, data binding, advanced data binding
Expressing your UI in JSON – plain, data binding, advanced data binding
Starcounter
 
Grokking: Data Engineering Course
Grokking: Data Engineering CourseGrokking: Data Engineering Course
Grokking: Data Engineering Course
Grokking VN
 
TechTalk #15 Grokking: The data processing journey at AhaMove
TechTalk #15 Grokking:  The data processing journey at AhaMoveTechTalk #15 Grokking:  The data processing journey at AhaMove
TechTalk #15 Grokking: The data processing journey at AhaMove
Grokking VN
 
Fashion blog
Fashion blogFashion blog
Fashion blog
Prasoon Prahaladan
 
Askourt - using the power of social networks to increase sales in eCommerce s...
Askourt - using the power of social networks to increase sales in eCommerce s...Askourt - using the power of social networks to increase sales in eCommerce s...
Askourt - using the power of social networks to increase sales in eCommerce s...
Tomer Limoey
 
TDC São Paulo - React presentation
TDC São Paulo - React presentationTDC São Paulo - React presentation
TDC São Paulo - React presentation
Danillo Corvalan
 
Breaking the Server-Client Divide with Node.js and React
Breaking the Server-Client Divide with Node.js and ReactBreaking the Server-Client Divide with Node.js and React
Breaking the Server-Client Divide with Node.js and React
Dejan Glozic
 
Creating Omnichannel Experiences with Loblaw Digital - eCommerce Toronto Meetup
Creating Omnichannel Experiences with Loblaw Digital - eCommerce Toronto MeetupCreating Omnichannel Experiences with Loblaw Digital - eCommerce Toronto Meetup
Creating Omnichannel Experiences with Loblaw Digital - eCommerce Toronto Meetup
Demac Media
 
Introduction to React Native & Redux
Introduction to React Native & ReduxIntroduction to React Native & Redux
Introduction to React Native & Redux
Barak Cohen
 
Get MEAN! Node.js and the MEAN stack
Get MEAN!  Node.js and the MEAN stackGet MEAN!  Node.js and the MEAN stack
Get MEAN! Node.js and the MEAN stack
Nicholas McClay
 
TDC2016SP - Trilha Frameworks JavaScript
TDC2016SP - Trilha Frameworks JavaScriptTDC2016SP - Trilha Frameworks JavaScript
TDC2016SP - Trilha Frameworks JavaScript
tdc-globalcode
 
Using ReactJS in AngularJS
Using ReactJS in AngularJSUsing ReactJS in AngularJS
Using ReactJS in AngularJS
Boris Dinkevich
 
Digital Marketing for a Modest Islamic Clothing store
Digital Marketing for a Modest Islamic Clothing storeDigital Marketing for a Modest Islamic Clothing store
Digital Marketing for a Modest Islamic Clothing store
Prolitus Technologies
 
How to increase engagement in fashion eCommerce stores
How to increase engagement in fashion eCommerce storesHow to increase engagement in fashion eCommerce stores
How to increase engagement in fashion eCommerce stores
Tomer Limoey
 
Backbone.js with React Views - Server Rendering, Virtual DOM, and More!
Backbone.js with React Views - Server Rendering, Virtual DOM, and More!Backbone.js with React Views - Server Rendering, Virtual DOM, and More!
Backbone.js with React Views - Server Rendering, Virtual DOM, and More!
Ryan Roemer
 
The MEAN Stack: MongoDB, ExpressJS, AngularJS and Node.js
The MEAN Stack: MongoDB, ExpressJS, AngularJS and Node.jsThe MEAN Stack: MongoDB, ExpressJS, AngularJS and Node.js
The MEAN Stack: MongoDB, ExpressJS, AngularJS and Node.js
MongoDB
 
The Evolution of Airbnb's Frontend
The Evolution of Airbnb's FrontendThe Evolution of Airbnb's Frontend
The Evolution of Airbnb's Frontend
Spike Brehm
 

Viewers also liked (20)

Grokking TechTalk #16: F**k bad CSS
Grokking TechTalk #16: F**k bad CSSGrokking TechTalk #16: F**k bad CSS
Grokking TechTalk #16: F**k bad CSS
 
Grokking TechTalk #16: React stack at lozi
Grokking TechTalk #16: React stack at loziGrokking TechTalk #16: React stack at lozi
Grokking TechTalk #16: React stack at lozi
 
Grokking TechTalk #16: Html js and three way binding
Grokking TechTalk #16: Html js and three way bindingGrokking TechTalk #16: Html js and three way binding
Grokking TechTalk #16: Html js and three way binding
 
Expressing your UI in JSON – plain, data binding, advanced data binding
Expressing your UI in JSON – plain, data binding, advanced data bindingExpressing your UI in JSON – plain, data binding, advanced data binding
Expressing your UI in JSON – plain, data binding, advanced data binding
 
Grokking: Data Engineering Course
Grokking: Data Engineering CourseGrokking: Data Engineering Course
Grokking: Data Engineering Course
 
TechTalk #15 Grokking: The data processing journey at AhaMove
TechTalk #15 Grokking:  The data processing journey at AhaMoveTechTalk #15 Grokking:  The data processing journey at AhaMove
TechTalk #15 Grokking: The data processing journey at AhaMove
 
Fashion blog
Fashion blogFashion blog
Fashion blog
 
Askourt - using the power of social networks to increase sales in eCommerce s...
Askourt - using the power of social networks to increase sales in eCommerce s...Askourt - using the power of social networks to increase sales in eCommerce s...
Askourt - using the power of social networks to increase sales in eCommerce s...
 
TDC São Paulo - React presentation
TDC São Paulo - React presentationTDC São Paulo - React presentation
TDC São Paulo - React presentation
 
Breaking the Server-Client Divide with Node.js and React
Breaking the Server-Client Divide with Node.js and ReactBreaking the Server-Client Divide with Node.js and React
Breaking the Server-Client Divide with Node.js and React
 
Creating Omnichannel Experiences with Loblaw Digital - eCommerce Toronto Meetup
Creating Omnichannel Experiences with Loblaw Digital - eCommerce Toronto MeetupCreating Omnichannel Experiences with Loblaw Digital - eCommerce Toronto Meetup
Creating Omnichannel Experiences with Loblaw Digital - eCommerce Toronto Meetup
 
Introduction to React Native & Redux
Introduction to React Native & ReduxIntroduction to React Native & Redux
Introduction to React Native & Redux
 
Get MEAN! Node.js and the MEAN stack
Get MEAN!  Node.js and the MEAN stackGet MEAN!  Node.js and the MEAN stack
Get MEAN! Node.js and the MEAN stack
 
TDC2016SP - Trilha Frameworks JavaScript
TDC2016SP - Trilha Frameworks JavaScriptTDC2016SP - Trilha Frameworks JavaScript
TDC2016SP - Trilha Frameworks JavaScript
 
Using ReactJS in AngularJS
Using ReactJS in AngularJSUsing ReactJS in AngularJS
Using ReactJS in AngularJS
 
Digital Marketing for a Modest Islamic Clothing store
Digital Marketing for a Modest Islamic Clothing storeDigital Marketing for a Modest Islamic Clothing store
Digital Marketing for a Modest Islamic Clothing store
 
How to increase engagement in fashion eCommerce stores
How to increase engagement in fashion eCommerce storesHow to increase engagement in fashion eCommerce stores
How to increase engagement in fashion eCommerce stores
 
Backbone.js with React Views - Server Rendering, Virtual DOM, and More!
Backbone.js with React Views - Server Rendering, Virtual DOM, and More!Backbone.js with React Views - Server Rendering, Virtual DOM, and More!
Backbone.js with React Views - Server Rendering, Virtual DOM, and More!
 
The MEAN Stack: MongoDB, ExpressJS, AngularJS and Node.js
The MEAN Stack: MongoDB, ExpressJS, AngularJS and Node.jsThe MEAN Stack: MongoDB, ExpressJS, AngularJS and Node.js
The MEAN Stack: MongoDB, ExpressJS, AngularJS and Node.js
 
The Evolution of Airbnb's Frontend
The Evolution of Airbnb's FrontendThe Evolution of Airbnb's Frontend
The Evolution of Airbnb's Frontend
 

Similar to Grokking TechTalk #16: Maybe functor in javascript

EcmaScript 6
EcmaScript 6 EcmaScript 6
EcmaScript 6
Manoj Kumar
 
ES6 PPT FOR 2016
ES6 PPT FOR 2016ES6 PPT FOR 2016
ES6 PPT FOR 2016
Manoj Kumar
 
Javascript development done right
Javascript development done rightJavascript development done right
Javascript development done right
Pawel Szulc
 
Beauty and Power of Go
Beauty and Power of GoBeauty and Power of Go
Beauty and Power of Go
Frank Müller
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
Dmitry Sheiko
 
Monads in javascript
Monads in javascriptMonads in javascript
Monads in javascript
Jana Karceska
 
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
 
No excuses, switch to kotlin
No excuses, switch to kotlinNo excuses, switch to kotlin
No excuses, switch to kotlin
Thijs Suijten
 
Ian 20150116 java script oop
Ian 20150116 java script oopIan 20150116 java script oop
Ian 20150116 java script oop
LearningTech
 
What's New In C# 7
What's New In C# 7What's New In C# 7
What's New In C# 7
Paulo Morgado
 
Java Question help needed In the program Fill the Add statements.pdf
Java Question  help needed In the program Fill the Add statements.pdfJava Question  help needed In the program Fill the Add statements.pdf
Java Question help needed In the program Fill the Add statements.pdf
kamdinrossihoungma74
 
TI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsTI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsEelco Visser
 
Kotlin For Android - Functions (part 3 of 7)
Kotlin For Android - Functions (part 3 of 7)Kotlin For Android - Functions (part 3 of 7)
Kotlin For Android - Functions (part 3 of 7)
Gesh Markov
 
Kotlin
KotlinKotlin
Introduction to Functional Programming
Introduction to Functional ProgrammingIntroduction to Functional Programming
Introduction to Functional Programming
Hoàng Lâm Huỳnh
 
Functional programming
Functional programming Functional programming
Functional programming
Nyarai Tinashe Gomiwa
 
Tuga IT 2017 - What's new in C# 7
Tuga IT 2017 - What's new in C# 7Tuga IT 2017 - What's new in C# 7
Tuga IT 2017 - What's new in C# 7
Paulo Morgado
 
Composition birds-and-recursion
Composition birds-and-recursionComposition birds-and-recursion
Composition birds-and-recursion
David Atchley
 
Internal workshop es6_2015
Internal workshop es6_2015Internal workshop es6_2015
Internal workshop es6_2015
Miguel Ruiz Rodriguez
 
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
 

Similar to Grokking TechTalk #16: Maybe functor in javascript (20)

EcmaScript 6
EcmaScript 6 EcmaScript 6
EcmaScript 6
 
ES6 PPT FOR 2016
ES6 PPT FOR 2016ES6 PPT FOR 2016
ES6 PPT FOR 2016
 
Javascript development done right
Javascript development done rightJavascript development done right
Javascript development done right
 
Beauty and Power of Go
Beauty and Power of GoBeauty and Power of Go
Beauty and Power of Go
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
 
Monads in javascript
Monads in javascriptMonads in javascript
Monads in javascript
 
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)
 
No excuses, switch to kotlin
No excuses, switch to kotlinNo excuses, switch to kotlin
No excuses, switch to kotlin
 
Ian 20150116 java script oop
Ian 20150116 java script oopIan 20150116 java script oop
Ian 20150116 java script oop
 
What's New In C# 7
What's New In C# 7What's New In C# 7
What's New In C# 7
 
Java Question help needed In the program Fill the Add statements.pdf
Java Question  help needed In the program Fill the Add statements.pdfJava Question  help needed In the program Fill the Add statements.pdf
Java Question help needed In the program Fill the Add statements.pdf
 
TI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsTI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class Functions
 
Kotlin For Android - Functions (part 3 of 7)
Kotlin For Android - Functions (part 3 of 7)Kotlin For Android - Functions (part 3 of 7)
Kotlin For Android - Functions (part 3 of 7)
 
Kotlin
KotlinKotlin
Kotlin
 
Introduction to Functional Programming
Introduction to Functional ProgrammingIntroduction to Functional Programming
Introduction to Functional Programming
 
Functional programming
Functional programming Functional programming
Functional programming
 
Tuga IT 2017 - What's new in C# 7
Tuga IT 2017 - What's new in C# 7Tuga IT 2017 - What's new in C# 7
Tuga IT 2017 - What's new in C# 7
 
Composition birds-and-recursion
Composition birds-and-recursionComposition birds-and-recursion
Composition birds-and-recursion
 
Internal workshop es6_2015
Internal workshop es6_2015Internal workshop es6_2015
Internal workshop es6_2015
 
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
 

More from Grokking VN

Grokking Techtalk #46: Lessons from years hacking and defending Vietnamese banks
Grokking Techtalk #46: Lessons from years hacking and defending Vietnamese banksGrokking Techtalk #46: Lessons from years hacking and defending Vietnamese banks
Grokking Techtalk #46: Lessons from years hacking and defending Vietnamese banks
Grokking VN
 
Grokking Techtalk #45: First Principles Thinking
Grokking Techtalk #45: First Principles ThinkingGrokking Techtalk #45: First Principles Thinking
Grokking Techtalk #45: First Principles Thinking
Grokking VN
 
Grokking Techtalk #42: Engineering challenges on building data platform for M...
Grokking Techtalk #42: Engineering challenges on building data platform for M...Grokking Techtalk #42: Engineering challenges on building data platform for M...
Grokking Techtalk #42: Engineering challenges on building data platform for M...
Grokking VN
 
Grokking Techtalk #43: Payment gateway demystified
Grokking Techtalk #43: Payment gateway demystifiedGrokking Techtalk #43: Payment gateway demystified
Grokking Techtalk #43: Payment gateway demystified
Grokking VN
 
Grokking Techtalk #40: Consistency and Availability tradeoff in database cluster
Grokking Techtalk #40: Consistency and Availability tradeoff in database clusterGrokking Techtalk #40: Consistency and Availability tradeoff in database cluster
Grokking Techtalk #40: Consistency and Availability tradeoff in database cluster
Grokking VN
 
Grokking Techtalk #40: AWS’s philosophy on designing MLOps platform
Grokking Techtalk #40: AWS’s philosophy on designing MLOps platformGrokking Techtalk #40: AWS’s philosophy on designing MLOps platform
Grokking Techtalk #40: AWS’s philosophy on designing MLOps platform
Grokking VN
 
Grokking Techtalk #39: Gossip protocol and applications
Grokking Techtalk #39: Gossip protocol and applicationsGrokking Techtalk #39: Gossip protocol and applications
Grokking Techtalk #39: Gossip protocol and applications
Grokking VN
 
Grokking Techtalk #39: How to build an event driven architecture with Kafka ...
 Grokking Techtalk #39: How to build an event driven architecture with Kafka ... Grokking Techtalk #39: How to build an event driven architecture with Kafka ...
Grokking Techtalk #39: How to build an event driven architecture with Kafka ...
Grokking VN
 
Grokking Techtalk #38: Escape Analysis in Go compiler
 Grokking Techtalk #38: Escape Analysis in Go compiler Grokking Techtalk #38: Escape Analysis in Go compiler
Grokking Techtalk #38: Escape Analysis in Go compiler
Grokking VN
 
Grokking Techtalk #37: Data intensive problem
 Grokking Techtalk #37: Data intensive problem Grokking Techtalk #37: Data intensive problem
Grokking Techtalk #37: Data intensive problem
Grokking VN
 
Grokking Techtalk #37: Software design and refactoring
 Grokking Techtalk #37: Software design and refactoring Grokking Techtalk #37: Software design and refactoring
Grokking Techtalk #37: Software design and refactoring
Grokking VN
 
Grokking TechTalk #35: Efficient spellchecking
Grokking TechTalk #35: Efficient spellcheckingGrokking TechTalk #35: Efficient spellchecking
Grokking TechTalk #35: Efficient spellchecking
Grokking VN
 
Grokking Techtalk #34: K8S On-premise: Incident & Lesson Learned ZaloPay Mer...
 Grokking Techtalk #34: K8S On-premise: Incident & Lesson Learned ZaloPay Mer... Grokking Techtalk #34: K8S On-premise: Incident & Lesson Learned ZaloPay Mer...
Grokking Techtalk #34: K8S On-premise: Incident & Lesson Learned ZaloPay Mer...
Grokking VN
 
Grokking TechTalk #33: High Concurrency Architecture at TIKI
Grokking TechTalk #33: High Concurrency Architecture at TIKIGrokking TechTalk #33: High Concurrency Architecture at TIKI
Grokking TechTalk #33: High Concurrency Architecture at TIKI
Grokking VN
 
Grokking TechTalk #33: Architecture of AI-First Systems - Engineering for Big...
Grokking TechTalk #33: Architecture of AI-First Systems - Engineering for Big...Grokking TechTalk #33: Architecture of AI-First Systems - Engineering for Big...
Grokking TechTalk #33: Architecture of AI-First Systems - Engineering for Big...
Grokking VN
 
SOLID & Design Patterns
SOLID & Design PatternsSOLID & Design Patterns
SOLID & Design Patterns
Grokking VN
 
Grokking TechTalk #31: Asynchronous Communications
Grokking TechTalk #31: Asynchronous CommunicationsGrokking TechTalk #31: Asynchronous Communications
Grokking TechTalk #31: Asynchronous Communications
Grokking VN
 
Grokking TechTalk #30: From App to Ecosystem: Lessons Learned at Scale
Grokking TechTalk #30: From App to Ecosystem: Lessons Learned at ScaleGrokking TechTalk #30: From App to Ecosystem: Lessons Learned at Scale
Grokking TechTalk #30: From App to Ecosystem: Lessons Learned at Scale
Grokking VN
 
Grokking TechTalk #29: Building Realtime Metrics Platform at LinkedIn
Grokking TechTalk #29: Building Realtime Metrics Platform at LinkedInGrokking TechTalk #29: Building Realtime Metrics Platform at LinkedIn
Grokking TechTalk #29: Building Realtime Metrics Platform at LinkedIn
Grokking VN
 
Grokking TechTalk #27: Optimal Binary Search Tree
Grokking TechTalk #27: Optimal Binary Search TreeGrokking TechTalk #27: Optimal Binary Search Tree
Grokking TechTalk #27: Optimal Binary Search Tree
Grokking VN
 

More from Grokking VN (20)

Grokking Techtalk #46: Lessons from years hacking and defending Vietnamese banks
Grokking Techtalk #46: Lessons from years hacking and defending Vietnamese banksGrokking Techtalk #46: Lessons from years hacking and defending Vietnamese banks
Grokking Techtalk #46: Lessons from years hacking and defending Vietnamese banks
 
Grokking Techtalk #45: First Principles Thinking
Grokking Techtalk #45: First Principles ThinkingGrokking Techtalk #45: First Principles Thinking
Grokking Techtalk #45: First Principles Thinking
 
Grokking Techtalk #42: Engineering challenges on building data platform for M...
Grokking Techtalk #42: Engineering challenges on building data platform for M...Grokking Techtalk #42: Engineering challenges on building data platform for M...
Grokking Techtalk #42: Engineering challenges on building data platform for M...
 
Grokking Techtalk #43: Payment gateway demystified
Grokking Techtalk #43: Payment gateway demystifiedGrokking Techtalk #43: Payment gateway demystified
Grokking Techtalk #43: Payment gateway demystified
 
Grokking Techtalk #40: Consistency and Availability tradeoff in database cluster
Grokking Techtalk #40: Consistency and Availability tradeoff in database clusterGrokking Techtalk #40: Consistency and Availability tradeoff in database cluster
Grokking Techtalk #40: Consistency and Availability tradeoff in database cluster
 
Grokking Techtalk #40: AWS’s philosophy on designing MLOps platform
Grokking Techtalk #40: AWS’s philosophy on designing MLOps platformGrokking Techtalk #40: AWS’s philosophy on designing MLOps platform
Grokking Techtalk #40: AWS’s philosophy on designing MLOps platform
 
Grokking Techtalk #39: Gossip protocol and applications
Grokking Techtalk #39: Gossip protocol and applicationsGrokking Techtalk #39: Gossip protocol and applications
Grokking Techtalk #39: Gossip protocol and applications
 
Grokking Techtalk #39: How to build an event driven architecture with Kafka ...
 Grokking Techtalk #39: How to build an event driven architecture with Kafka ... Grokking Techtalk #39: How to build an event driven architecture with Kafka ...
Grokking Techtalk #39: How to build an event driven architecture with Kafka ...
 
Grokking Techtalk #38: Escape Analysis in Go compiler
 Grokking Techtalk #38: Escape Analysis in Go compiler Grokking Techtalk #38: Escape Analysis in Go compiler
Grokking Techtalk #38: Escape Analysis in Go compiler
 
Grokking Techtalk #37: Data intensive problem
 Grokking Techtalk #37: Data intensive problem Grokking Techtalk #37: Data intensive problem
Grokking Techtalk #37: Data intensive problem
 
Grokking Techtalk #37: Software design and refactoring
 Grokking Techtalk #37: Software design and refactoring Grokking Techtalk #37: Software design and refactoring
Grokking Techtalk #37: Software design and refactoring
 
Grokking TechTalk #35: Efficient spellchecking
Grokking TechTalk #35: Efficient spellcheckingGrokking TechTalk #35: Efficient spellchecking
Grokking TechTalk #35: Efficient spellchecking
 
Grokking Techtalk #34: K8S On-premise: Incident & Lesson Learned ZaloPay Mer...
 Grokking Techtalk #34: K8S On-premise: Incident & Lesson Learned ZaloPay Mer... Grokking Techtalk #34: K8S On-premise: Incident & Lesson Learned ZaloPay Mer...
Grokking Techtalk #34: K8S On-premise: Incident & Lesson Learned ZaloPay Mer...
 
Grokking TechTalk #33: High Concurrency Architecture at TIKI
Grokking TechTalk #33: High Concurrency Architecture at TIKIGrokking TechTalk #33: High Concurrency Architecture at TIKI
Grokking TechTalk #33: High Concurrency Architecture at TIKI
 
Grokking TechTalk #33: Architecture of AI-First Systems - Engineering for Big...
Grokking TechTalk #33: Architecture of AI-First Systems - Engineering for Big...Grokking TechTalk #33: Architecture of AI-First Systems - Engineering for Big...
Grokking TechTalk #33: Architecture of AI-First Systems - Engineering for Big...
 
SOLID & Design Patterns
SOLID & Design PatternsSOLID & Design Patterns
SOLID & Design Patterns
 
Grokking TechTalk #31: Asynchronous Communications
Grokking TechTalk #31: Asynchronous CommunicationsGrokking TechTalk #31: Asynchronous Communications
Grokking TechTalk #31: Asynchronous Communications
 
Grokking TechTalk #30: From App to Ecosystem: Lessons Learned at Scale
Grokking TechTalk #30: From App to Ecosystem: Lessons Learned at ScaleGrokking TechTalk #30: From App to Ecosystem: Lessons Learned at Scale
Grokking TechTalk #30: From App to Ecosystem: Lessons Learned at Scale
 
Grokking TechTalk #29: Building Realtime Metrics Platform at LinkedIn
Grokking TechTalk #29: Building Realtime Metrics Platform at LinkedInGrokking TechTalk #29: Building Realtime Metrics Platform at LinkedIn
Grokking TechTalk #29: Building Realtime Metrics Platform at LinkedIn
 
Grokking TechTalk #27: Optimal Binary Search Tree
Grokking TechTalk #27: Optimal Binary Search TreeGrokking TechTalk #27: Optimal Binary Search Tree
Grokking TechTalk #27: Optimal Binary Search Tree
 

Recently uploaded

Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
Safe Software
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Albert Hoitingh
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
KatiaHIMEUR1
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
Dorra BARTAGUIZ
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
Product School
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
Paul Groth
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
Product School
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
RTTS
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
Cheryl Hung
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
Product School
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Tobias Schneck
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
Elena Simperl
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
DianaGray10
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
OnBoard
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
Frank van Harmelen
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Inflectra
 

Recently uploaded (20)

Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
 

Grokking TechTalk #16: Maybe functor in javascript

  • 1. Maybe Functor in Javascript Another approach to null handling 1
  • 2. 2
  • 3. Origin of Null Pointer Exception ● Sir Tony Hoare was designing type systems for the language ALGOL W and he put “Null Pointer Exception” as part of the language, because “because it was so easy to implement” ● In 2009, he called it “The Billion Dollar Mistake” 3
  • 4. What we want: getCountry('vn').getCity('HCMC').population; What we have to do var country = getCountry('vn'); if (country !== null) { var city = country.getCity('HCMC'); if (city !== null) { var population = city.population; } } How do we fight NULL? 4 Drawbacks: ● Looks complicated ● Error-prone, especially when there are many nesting ifs ● Tedious to write ● Declares a lot of useless variables
  • 5. ● A Functor is a container of a value Introduction to Functor 5 A value A container of value ● A simple Functor can be implemented through an ES6 class class Functor { constructor(value) { this.value = value; } }
  • 6. One important thing about Functor 6 By definition, a functor needs to implement a map function
  • 7. Remember Array Map? 7 Let’s look at Array’s map function. var addOne = (x) => x + 1; var square = (x) => x * x; var result = [1, 2, 3] .map(addOne) // [2, 3, 4] .map(square); // [4, 9, 16]
  • 8. Implement map for Functor 8 class Functor { constructor(value) { this.value = value; } map(fn) { var newValue = fn(this.value); return new Functor(newValue); } }
  • 9. Let’s see it in action (1) 9 var addOne = (x) => x + 1; var functorOf6 = new Functor(5).map(addOne); // Functor(6)
  • 10. It can also work with any value, for example, an object: var toUpperCase = (str) => str.toUpperCase(); var exciting = (someName) => someName + ’!!!!!!!’; var value = { name: 'grokking' }; var containerOfValue = new Functor(value) .map(thing => thing.name) // Functor(‘grokking’) .map(toUpperCase) // Functor(‘GROKKING’) .map(exciting); // Functor(‘GROKKING!!!!!!!’) Let’s see it in action (2) 10
  • 11. Notice that our actual value is still inside the Functor. var functorOf36 = new Functor(5) .map(addOne) // Functor(6) .map(square); // Functor(36) var result = functorOf36 + 100; // Functor(36) + 100 ??????? How to get the value inside Functor 11 Let’s add another method to Functor to extract the value. class Functor { get() { return this.value; } }
  • 12. var valueInside = new Functor(5) .map(addOne) // Functor(6) .map(square); // Functor(36) .get(); // 36 var toUpperCase = (str) => str.toUpperCase(); var exciting = (someName) => someName + '!!!!!!'; var valueInside = new Functor({ name: 'grokking' }) .map(people => people.name) // Functor(‘grokking’) .map(toUpperCase) // Functor(‘GROKKING’) .map(exciting); // Functor(‘GROKKING!!!!!!!’) .get(); // 'GROKKING!!!!!!!' Now we can get the value inside Functor 12
  • 13. class Functor { constructor(value) { this.value = value; } map(fn) { var newValue = fn(this.value); return new Maybe(newValue); } get() { return this.value; } } Full implementation of Functor 13
  • 14. var addOne = (x) => null; // we return Null var square = (x) => x * x; var valueInside = new Functor(1) .map(addOne) // Functor(null) .map(square); // Functor(null * null) ???? .get(); // ???? But we are still affected by NULL 14 The solution is to turn our functor into a Maybe
  • 15. ● Maybe is a kind of Functor that is Null- friendly. Real magic happens in the map function ● Maybe that contains a real value (not null) is usually called a Just / Some ● Maybe that contains null value is usually called a Nothing / None Introduction to Maybe 15 Maybe(value) = Just(value) Maybe(null) = Nothing
  • 16. class Maybe { constructor(value) { this.value = value; } map(fn) { if (this.value !== null) { // Magic happens here var newValue = fn(this.value); return new Maybe(newValue); } return new Maybe(null); } getOrElse(fallBackValue) { return (this.value === null) ? this.value : fallBackValue; } } Let’s implement Maybe 16
  • 17. It’s pretty much the same as Functor’s example. The only difference is that we use getOrElse instead of get var addOne = (x) => x + 1; var square = (x) => x * x; var result = new Maybe(3) .map(addOne) // Maybe(4) .map(square) // Maybe(16) .getOrElse(0); // 16 Maybe in action 17
  • 18. When Maybe contains NULL, it will not map anymore var result = new Maybe(3) .map(x => null) // Maybe(null) .map(x => x * x) // Maybe(null) .getOrElse(0); // 0 var result = new Maybe(3) .map(x => x + 1) // Maybe(4) .map(x => null) // Maybe(null) .getOrElse(0); // 0 When Null happens 18
  • 19. Some real world examples var family = { grandma: { mother: { you: 'YOUR NAME HERE' } } }; var you = new Maybe(family.grandma) .map(grandma => grandma.mother) .map(mother => mother.you) .getOrElse('DEFAULT NAME'); // returns “YOUR NAME HERE” var family = { grandma: null }; var you = new Maybe(family.grandma) .map(grandma => grandma.mother) .map(mother => mother.you) .getOrElse('DEFAULT NAME'); // returns “DEFAULT NAME” 19 We can use it to safely access nested objects
  • 20. Compare with what we used to do 20 var you = family.grandma.mother.you || 'DEFAULT NAME'; var you = 'DEFAULT NAME'; if (family.grandma && family.grandma.mother && family.grandma.mother.you) { you = family.grandma.mother.you; } var you = new Maybe(family.grandma) .map(grandma => grandma.mother) .map(mother => mother.you) .getOrElse('DEFAULT NAME'); Short, but unsafe Safe, but long and nested Safe and flattened
  • 21. var population = new Maybe(getCountry('vn')) .map(country => country.getCity('HCMC')) .map(city => city.population) .getOrElse(0); Some real world examples var country = getCountry('vn'); if (country !== null) { var city = country.getCity('HCMC'); if (city !== null) { var population = city.population; } } 21 We can rewrite our example earlier Into shorter and flattened code
  • 22. ● Is just a container of value ● Is a fundamental concept in Functional Programming. From there you can explore Applicative and Monad ● Is a kind of functor that checks null on each map ● Helps flatten your code ● Is used widely in many other languages: - Haskell, Elm: Maybe Recap 22 Maybe Functor
  • 23. References ● https://github.com/fantasyland/fantasy-land Fantasy Land Specification ● https://cwmyers.github.io/monet.js/ Powerful abstractions for Javascript ● http://adit.io/posts/2013-04-17-functors,_applicatives,_and_monads_in_pictures.html Functor, Applicatives, Monads in pictures ● https://en.wikipedia.org/wiki/Functor (looks scary with all the math) ● http://www.mokacoding.com/blog/functor-applicative-monads-in-pictures/ (Maybe in Swift) ● http://www.oracle.com/technetwork/articles/java/java8-optional-2175753.html Java 8 Optional 23