SlideShare a Scribd company logo
1 of 13
Download to read offline
Monads in Javascript
Jana Karcheska
Netcetera, Skopje
What makes apps messy?
• Impurity
• Nulls
• Callbacks
• Errors
• Side effects
Stay pure
• Separate the pure from the impure
• Date, random
• DOM manipulation
• Handling user input
What are monads?
• Category theory
• You don’t need to know category theory to use monads
• Functional programming
• Haskell – loophole to introduce the illusion of impurity
Today’s example
Our goal for today
var matchElement = function(searchWord) {
return compose(_.curry(matchText)(searchWord), getCommentFromElement);
}
var doSearch = function(searchWord) {
return _.filter(matchElement(searchWord))(getAllCommentElements());
}
var getResults = compose(mjoin, map(_.forEach(applyResultStyle)), map(doSearch), Maybe, getSearchWord);
function search() {
var results = getResults("#searchWord")
var resultsNumberElement = $('#resultsNumber');
resultsNumberElement.text('Results: ' + results.length);
}
// get the search word from the search input field
function getSearchWord(elName) {
return $(elName).val();
}
// find all comment p elements
function getAllCommentElements() {
return $("p").toArray();
}
// get comment text from p element
function getCommentFromElement(el) {
return $(el).text();
}
// text matching
function matchText(searchWord, comment) {
return comment.split(searchWord).length - 1;
}
// apply style to mark search results
function applyResultStyle(element) {
$(element).parent().css({'border-style': 'dashed', 'border-color' : 'pink'});
}
function search() {
var searchWord = $("#searchWord").val();
var allCommentElements = getAllCommentElements();
var resultsNumber = 0;
allCommentElements.each(function (index, el) {
if (matchText($(el).text(), searchWord)) {
applyResultStyle($(el).parent());
resultsNumber++;
}
});
var resultsNumberElement = $('#resultsNumber');
resultsNumberElement.text('Results: ' + resultsNumber);
}
// get the search word from the search input field
function getSearchWord(elName) {
return $(elName).val();
}
// find all comment p elements
function getAllCommentElements() {
return $("p").toArray();
}
// get comment text from p element
function getCommentFromElement(el) {
return $(el).text();
}
// text matching
function matchText(searchWord, comment) {
return comment.split(searchWord).length - 1;
}
// apply style to mark search results
function applyResultStyle(element) {
$(element).parent().css({'border-style': 'dashed', 'border-color' : 'pink'});
}
Example – imperative programming
function search() {
var searchWord = $("#searchWord").val();
var allCommentElements = getAllCommentElements();
var resultsNumber = 0;
allCommentElements.each(function (index, el) {
if (matchText($(el).text(), searchWord)) {
applyResultStyle($(el).parent());
resultsNumber++;
}
});
var resultsNumberElement = $('#resultsNumber');
resultsNumberElement.text('Results: ' + resultsNumber);
}
map - compose
var _Container = function (val) {
this.val = val;
}
var Container = function(x) { return new _Container(x); }
Container(1);
// > _Container { val:1 }
_Container.prototype.map = function(f) {
return Container(f(this.val));
}
Container(“jana”).map(capitalize)
// > Container(“Jana”)
var map = _.curry(function(f,obj) {
return obj.map(f);
}
map(capitalize, Container(“jana”);
map(compose(first, reverse), Container(“jana”));
_Maybe.prototype.map = function(f) {
return this.val ? Maybe(f(this.val)) : Maybe(null);
}
map(capitalize, Maybe(“jana”);
// > Maybe(“Jana”)
var name = null;
map(capitalize, Maybe(name);
// > Maybe(null)
map(compose(first, reverse), Container(“jana”));
Functors – any object or data structure that you
can map over
Maybe
Future
IO
Either
EventStream
Monads
• Nested computations
• mjoin
• chain
We can implement mjoin, chain or both
var chain = function(f) {
return compose(mjoin, map(f));
}
var mjoin = chain(id);
// nested mappings
var renderPage = compose(map(map(ourRenderFunction), ourPrepareFunction);
var renderPage = compose(mjoin, map(ourRenderFunction), ourPrepareFunction);
Example – with monads
var matchElement = function(searchWord) {
return compose(_.curry(matchText)(searchWord), getCommentFromElement);
}
var doSearch = function(searchWord) {
return _.filter(matchElement(searchWord))(getAllCommentElements());
}
var getResults = compose(mjoin, map(_.forEach(applyResultStyle)), map(doSearch), Maybe, getSearchWord);
function search() {
var results = getResults("#searchWord")
var resultsNumberElement = $('#resultsNumber');
resultsNumberElement.text('Results: ' + results.length);
}
Where do we use monads?
• Ajax libraries
• Promise implementations
• JQuery is a monad
We are used to seeing custom names:
• Promise(x).then(f)
While in terms of algebraic functors they are defined generally
• map(f, Promise(x))
Where do we use monads?
• Ajax libraries
• Promise implementations
• JQuery is a monad
We are used to seeing custom names:
• Promise(x).then(f)
While in terms of algebraic functors they are defined generally
• map(f, Promise(x))
References
• ramdajs
• http://ramdajs.com/repl/?v=0.18.0
• auto curried functions
• arguments arranged suitable for currying
• fantasy-land
• Algebraic JavaScript Specification
• Lots of modules and libs
• pointless-fantasy: a point-free implementation
• ttps://github.com/douglascrockford/monad

More Related Content

What's hot

Thinking Functionally with JavaScript
Thinking Functionally with JavaScriptThinking Functionally with JavaScript
Thinking Functionally with JavaScriptLuis Atencio
 
“SOLID principles in PHP – how to apply them in PHP and why should we care“ b...
“SOLID principles in PHP – how to apply them in PHP and why should we care“ b...“SOLID principles in PHP – how to apply them in PHP and why should we care“ b...
“SOLID principles in PHP – how to apply them in PHP and why should we care“ b...DevClub_lv
 
Автотесты для картинок
Автотесты для картинокАвтотесты для картинок
Автотесты для картинокPetr Trofimov
 
ES6 Primer
ES6 PrimerES6 Primer
ES6 Primerroblund
 
Understanding storage class using nm
Understanding storage class using nmUnderstanding storage class using nm
Understanding storage class using nmmohamed sikander
 
Monad Transformers In The Wild
Monad Transformers In The WildMonad Transformers In The Wild
Monad Transformers In The WildStackMob Inc
 
Code moi une RH! (PHP tour 2017)
Code moi une RH! (PHP tour 2017)Code moi une RH! (PHP tour 2017)
Code moi une RH! (PHP tour 2017)Arnaud Langlade
 
CBSE Class XII Comp sc practical file
CBSE Class XII Comp sc practical fileCBSE Class XII Comp sc practical file
CBSE Class XII Comp sc practical filePranav Ghildiyal
 
Swift 함수 커링 사용하기
Swift 함수 커링 사용하기Swift 함수 커링 사용하기
Swift 함수 커링 사용하기진성 오
 
20180721 code defragment
20180721 code defragment20180721 code defragment
20180721 code defragmentChiwon Song
 
RESTful API using scalaz (3)
RESTful API using scalaz (3)RESTful API using scalaz (3)
RESTful API using scalaz (3)Yeshwanth Kumar
 
Data Structures Practical File
Data Structures Practical File Data Structures Practical File
Data Structures Practical File Harjinder Singh
 
RxSwift 활용하기 - Let'Swift 2017
RxSwift 활용하기 - Let'Swift 2017RxSwift 활용하기 - Let'Swift 2017
RxSwift 활용하기 - Let'Swift 2017Wanbok Choi
 

What's hot (20)

Thinking Functionally with JavaScript
Thinking Functionally with JavaScriptThinking Functionally with JavaScript
Thinking Functionally with JavaScript
 
“SOLID principles in PHP – how to apply them in PHP and why should we care“ b...
“SOLID principles in PHP – how to apply them in PHP and why should we care“ b...“SOLID principles in PHP – how to apply them in PHP and why should we care“ b...
“SOLID principles in PHP – how to apply them in PHP and why should we care“ b...
 
Автотесты для картинок
Автотесты для картинокАвтотесты для картинок
Автотесты для картинок
 
ES6 Primer
ES6 PrimerES6 Primer
ES6 Primer
 
Understanding storage class using nm
Understanding storage class using nmUnderstanding storage class using nm
Understanding storage class using nm
 
Monad Transformers In The Wild
Monad Transformers In The WildMonad Transformers In The Wild
Monad Transformers In The Wild
 
Scheme 核心概念(一)
Scheme 核心概念(一)Scheme 核心概念(一)
Scheme 核心概念(一)
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
 
Code moi une RH! (PHP tour 2017)
Code moi une RH! (PHP tour 2017)Code moi une RH! (PHP tour 2017)
Code moi une RH! (PHP tour 2017)
 
CBSE Class XII Comp sc practical file
CBSE Class XII Comp sc practical fileCBSE Class XII Comp sc practical file
CBSE Class XII Comp sc practical file
 
Swift 함수 커링 사용하기
Swift 함수 커링 사용하기Swift 함수 커링 사용하기
Swift 함수 커링 사용하기
 
20180721 code defragment
20180721 code defragment20180721 code defragment
20180721 code defragment
 
RESTful API using scalaz (3)
RESTful API using scalaz (3)RESTful API using scalaz (3)
RESTful API using scalaz (3)
 
Pratik Bakane C++
Pratik Bakane C++Pratik Bakane C++
Pratik Bakane C++
 
Data Structures Practical File
Data Structures Practical File Data Structures Practical File
Data Structures Practical File
 
RxSwift 활용하기 - Let'Swift 2017
RxSwift 활용하기 - Let'Swift 2017RxSwift 활용하기 - Let'Swift 2017
RxSwift 활용하기 - Let'Swift 2017
 
Pratik Bakane C++
Pratik Bakane C++Pratik Bakane C++
Pratik Bakane C++
 
week-21x
week-21xweek-21x
week-21x
 
Sigma type
Sigma typeSigma type
Sigma type
 
mobl
moblmobl
mobl
 

Viewers also liked

Awesomely descriptive JavaScript with monads
Awesomely descriptive JavaScript with monadsAwesomely descriptive JavaScript with monads
Awesomely descriptive JavaScript with monadsMichal Nowak
 
HENIO ANDRES NARVAEZ DAZA
HENIO ANDRES NARVAEZ DAZAHENIO ANDRES NARVAEZ DAZA
HENIO ANDRES NARVAEZ DAZAAndres Narvaez
 
Casi di innovazione sociale, le slide di Linda Serra
Casi di innovazione sociale, le slide di Linda SerraCasi di innovazione sociale, le slide di Linda Serra
Casi di innovazione sociale, le slide di Linda SerraRavenna Future Lessons
 
Progettare la condivisione
Progettare la condivisione Progettare la condivisione
Progettare la condivisione luca corsato
 
WRI 203 Lecture 1- Introduction to Expressive Writing
WRI 203 Lecture 1- Introduction to Expressive WritingWRI 203 Lecture 1- Introduction to Expressive Writing
WRI 203 Lecture 1- Introduction to Expressive WritingRahul Sethi
 
Questions and anwers
Questions and anwersQuestions and anwers
Questions and anwersateixidoca1
 
Documento informativo
Documento informativoDocumento informativo
Documento informativoBanca Ifis
 
United breweries limited
United breweries limitedUnited breweries limited
United breweries limitedRavin Gandhi
 

Viewers also liked (17)

Awesomely descriptive JavaScript with monads
Awesomely descriptive JavaScript with monadsAwesomely descriptive JavaScript with monads
Awesomely descriptive JavaScript with monads
 
014625
014625014625
014625
 
Bài giới thiệu
Bài giới thiệuBài giới thiệu
Bài giới thiệu
 
Comunicato stampa sindaco
Comunicato stampa sindacoComunicato stampa sindaco
Comunicato stampa sindaco
 
21st Century Schools and Learners
21st Century Schools and Learners21st Century Schools and Learners
21st Century Schools and Learners
 
Stampa 3D & Coworking
Stampa 3D & CoworkingStampa 3D & Coworking
Stampa 3D & Coworking
 
HENIO ANDRES NARVAEZ DAZA
HENIO ANDRES NARVAEZ DAZAHENIO ANDRES NARVAEZ DAZA
HENIO ANDRES NARVAEZ DAZA
 
Casi di innovazione sociale, le slide di Linda Serra
Casi di innovazione sociale, le slide di Linda SerraCasi di innovazione sociale, le slide di Linda Serra
Casi di innovazione sociale, le slide di Linda Serra
 
Progettare la condivisione
Progettare la condivisione Progettare la condivisione
Progettare la condivisione
 
Village survey
Village surveyVillage survey
Village survey
 
WRI 203 Lecture 1- Introduction to Expressive Writing
WRI 203 Lecture 1- Introduction to Expressive WritingWRI 203 Lecture 1- Introduction to Expressive Writing
WRI 203 Lecture 1- Introduction to Expressive Writing
 
Questions and anwers
Questions and anwersQuestions and anwers
Questions and anwers
 
Village Survey
Village SurveyVillage Survey
Village Survey
 
Documento informativo
Documento informativoDocumento informativo
Documento informativo
 
United breweries limited
United breweries limitedUnited breweries limited
United breweries limited
 
Vijay mallay
Vijay mallayVijay mallay
Vijay mallay
 
United Spirits Ltd
United Spirits LtdUnited Spirits Ltd
United Spirits Ltd
 

Similar to Monads in javascript

TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript IntroductionDmitry Sheiko
 
Google Guava for cleaner code
Google Guava for cleaner codeGoogle Guava for cleaner code
Google Guava for cleaner codeMite Mitreski
 
Why async and functional programming in PHP7 suck and how to get overr it?
Why async and functional programming in PHP7 suck and how to get overr it?Why async and functional programming in PHP7 suck and how to get overr it?
Why async and functional programming in PHP7 suck and how to get overr it?Lucas Witold Adamus
 
PHPCon 2016: PHP7 by Witek Adamus / XSolve
PHPCon 2016: PHP7 by Witek Adamus / XSolvePHPCon 2016: PHP7 by Witek Adamus / XSolve
PHPCon 2016: PHP7 by Witek Adamus / XSolveXSolve
 
JavaScript for PHP developers
JavaScript for PHP developersJavaScript for PHP developers
JavaScript for PHP developersStoyan Stefanov
 
Creating an Uber Clone - Part XVIII - Transcript.pdf
Creating an Uber Clone - Part XVIII - Transcript.pdfCreating an Uber Clone - Part XVIII - Transcript.pdf
Creating an Uber Clone - Part XVIII - Transcript.pdfShaiAlmog1
 
Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02Seri Moth
 
Functional programming using underscorejs
Functional programming using underscorejsFunctional programming using underscorejs
Functional programming using underscorejs偉格 高
 
Bindings: the zen of montage
Bindings: the zen of montageBindings: the zen of montage
Bindings: the zen of montageKris Kowal
 
PHP and Rich Internet Applications
PHP and Rich Internet ApplicationsPHP and Rich Internet Applications
PHP and Rich Internet Applicationselliando dias
 
Javascript 基础
Javascript 基础Javascript 基础
Javascript 基础Alipay
 
PHP and Rich Internet Applications
PHP and Rich Internet ApplicationsPHP and Rich Internet Applications
PHP and Rich Internet Applicationselliando dias
 
Composition in JavaScript
Composition in JavaScriptComposition in JavaScript
Composition in JavaScriptJosh Mock
 
A Functional Guide to Cat Herding with PHP Generators
A Functional Guide to Cat Herding with PHP GeneratorsA Functional Guide to Cat Herding with PHP Generators
A Functional Guide to Cat Herding with PHP GeneratorsMark Baker
 
JavaScript and UI Architecture Best Practices
JavaScript and UI Architecture Best PracticesJavaScript and UI Architecture Best Practices
JavaScript and UI Architecture Best PracticesSiarhei Barysiuk
 
Durian: a PHP 5.5 microframework with generator-style middleware
Durian: a PHP 5.5 microframework with generator-style middlewareDurian: a PHP 5.5 microframework with generator-style middleware
Durian: a PHP 5.5 microframework with generator-style middlewareKuan Yen Heng
 

Similar to Monads in javascript (20)

TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
 
Google Guava for cleaner code
Google Guava for cleaner codeGoogle Guava for cleaner code
Google Guava for cleaner code
 
Why async and functional programming in PHP7 suck and how to get overr it?
Why async and functional programming in PHP7 suck and how to get overr it?Why async and functional programming in PHP7 suck and how to get overr it?
Why async and functional programming in PHP7 suck and how to get overr it?
 
PHPCon 2016: PHP7 by Witek Adamus / XSolve
PHPCon 2016: PHP7 by Witek Adamus / XSolvePHPCon 2016: PHP7 by Witek Adamus / XSolve
PHPCon 2016: PHP7 by Witek Adamus / XSolve
 
JavaScript for PHP developers
JavaScript for PHP developersJavaScript for PHP developers
JavaScript for PHP developers
 
Short intro to ECMAScript
Short intro to ECMAScriptShort intro to ECMAScript
Short intro to ECMAScript
 
Creating an Uber Clone - Part XVIII - Transcript.pdf
Creating an Uber Clone - Part XVIII - Transcript.pdfCreating an Uber Clone - Part XVIII - Transcript.pdf
Creating an Uber Clone - Part XVIII - Transcript.pdf
 
Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02
 
Functional programming using underscorejs
Functional programming using underscorejsFunctional programming using underscorejs
Functional programming using underscorejs
 
Bindings: the zen of montage
Bindings: the zen of montageBindings: the zen of montage
Bindings: the zen of montage
 
PHP and Rich Internet Applications
PHP and Rich Internet ApplicationsPHP and Rich Internet Applications
PHP and Rich Internet Applications
 
Wakanday JS201 Best Practices
Wakanday JS201 Best PracticesWakanday JS201 Best Practices
Wakanday JS201 Best Practices
 
Javascript 基础
Javascript 基础Javascript 基础
Javascript 基础
 
PHP and Rich Internet Applications
PHP and Rich Internet ApplicationsPHP and Rich Internet Applications
PHP and Rich Internet Applications
 
Composition in JavaScript
Composition in JavaScriptComposition in JavaScript
Composition in JavaScript
 
A Functional Guide to Cat Herding with PHP Generators
A Functional Guide to Cat Herding with PHP GeneratorsA Functional Guide to Cat Herding with PHP Generators
A Functional Guide to Cat Herding with PHP Generators
 
JavaScript and UI Architecture Best Practices
JavaScript and UI Architecture Best PracticesJavaScript and UI Architecture Best Practices
JavaScript and UI Architecture Best Practices
 
SDC - Einführung in Scala
SDC - Einführung in ScalaSDC - Einführung in Scala
SDC - Einführung in Scala
 
Functional programming with php7
Functional programming with php7Functional programming with php7
Functional programming with php7
 
Durian: a PHP 5.5 microframework with generator-style middleware
Durian: a PHP 5.5 microframework with generator-style middlewareDurian: a PHP 5.5 microframework with generator-style middleware
Durian: a PHP 5.5 microframework with generator-style middleware
 

Recently uploaded

What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...Technogeeks
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...confluent
 
VK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web DevelopmentVK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web Developmentvyaparkranti
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfStefano Stabellini
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsChristian Birchler
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsSafe Software
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceBrainSell Technologies
 
Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identityteam-WIBU
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 
Sending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdfSending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdf31events.com
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Mater
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Cizo Technology Services
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Rob Geurden
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Velvetech LLC
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 

Recently uploaded (20)

What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...
 
2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
 
Advantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your BusinessAdvantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your Business
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
VK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web DevelopmentVK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web Development
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdf
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data Streams
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. Salesforce
 
Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identity
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
Sending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdfSending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdf
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 

Monads in javascript

  • 1. Monads in Javascript Jana Karcheska Netcetera, Skopje
  • 2. What makes apps messy? • Impurity • Nulls • Callbacks • Errors • Side effects
  • 3. Stay pure • Separate the pure from the impure • Date, random • DOM manipulation • Handling user input
  • 4. What are monads? • Category theory • You don’t need to know category theory to use monads • Functional programming • Haskell – loophole to introduce the illusion of impurity
  • 6. Our goal for today var matchElement = function(searchWord) { return compose(_.curry(matchText)(searchWord), getCommentFromElement); } var doSearch = function(searchWord) { return _.filter(matchElement(searchWord))(getAllCommentElements()); } var getResults = compose(mjoin, map(_.forEach(applyResultStyle)), map(doSearch), Maybe, getSearchWord); function search() { var results = getResults("#searchWord") var resultsNumberElement = $('#resultsNumber'); resultsNumberElement.text('Results: ' + results.length); } // get the search word from the search input field function getSearchWord(elName) { return $(elName).val(); } // find all comment p elements function getAllCommentElements() { return $("p").toArray(); } // get comment text from p element function getCommentFromElement(el) { return $(el).text(); } // text matching function matchText(searchWord, comment) { return comment.split(searchWord).length - 1; } // apply style to mark search results function applyResultStyle(element) { $(element).parent().css({'border-style': 'dashed', 'border-color' : 'pink'}); } function search() { var searchWord = $("#searchWord").val(); var allCommentElements = getAllCommentElements(); var resultsNumber = 0; allCommentElements.each(function (index, el) { if (matchText($(el).text(), searchWord)) { applyResultStyle($(el).parent()); resultsNumber++; } }); var resultsNumberElement = $('#resultsNumber'); resultsNumberElement.text('Results: ' + resultsNumber); } // get the search word from the search input field function getSearchWord(elName) { return $(elName).val(); } // find all comment p elements function getAllCommentElements() { return $("p").toArray(); } // get comment text from p element function getCommentFromElement(el) { return $(el).text(); } // text matching function matchText(searchWord, comment) { return comment.split(searchWord).length - 1; } // apply style to mark search results function applyResultStyle(element) { $(element).parent().css({'border-style': 'dashed', 'border-color' : 'pink'}); }
  • 7. Example – imperative programming function search() { var searchWord = $("#searchWord").val(); var allCommentElements = getAllCommentElements(); var resultsNumber = 0; allCommentElements.each(function (index, el) { if (matchText($(el).text(), searchWord)) { applyResultStyle($(el).parent()); resultsNumber++; } }); var resultsNumberElement = $('#resultsNumber'); resultsNumberElement.text('Results: ' + resultsNumber); }
  • 8. map - compose var _Container = function (val) { this.val = val; } var Container = function(x) { return new _Container(x); } Container(1); // > _Container { val:1 } _Container.prototype.map = function(f) { return Container(f(this.val)); } Container(“jana”).map(capitalize) // > Container(“Jana”) var map = _.curry(function(f,obj) { return obj.map(f); } map(capitalize, Container(“jana”); map(compose(first, reverse), Container(“jana”)); _Maybe.prototype.map = function(f) { return this.val ? Maybe(f(this.val)) : Maybe(null); } map(capitalize, Maybe(“jana”); // > Maybe(“Jana”) var name = null; map(capitalize, Maybe(name); // > Maybe(null) map(compose(first, reverse), Container(“jana”)); Functors – any object or data structure that you can map over Maybe Future IO Either EventStream
  • 9. Monads • Nested computations • mjoin • chain We can implement mjoin, chain or both var chain = function(f) { return compose(mjoin, map(f)); } var mjoin = chain(id); // nested mappings var renderPage = compose(map(map(ourRenderFunction), ourPrepareFunction); var renderPage = compose(mjoin, map(ourRenderFunction), ourPrepareFunction);
  • 10. Example – with monads var matchElement = function(searchWord) { return compose(_.curry(matchText)(searchWord), getCommentFromElement); } var doSearch = function(searchWord) { return _.filter(matchElement(searchWord))(getAllCommentElements()); } var getResults = compose(mjoin, map(_.forEach(applyResultStyle)), map(doSearch), Maybe, getSearchWord); function search() { var results = getResults("#searchWord") var resultsNumberElement = $('#resultsNumber'); resultsNumberElement.text('Results: ' + results.length); }
  • 11. Where do we use monads? • Ajax libraries • Promise implementations • JQuery is a monad We are used to seeing custom names: • Promise(x).then(f) While in terms of algebraic functors they are defined generally • map(f, Promise(x))
  • 12. Where do we use monads? • Ajax libraries • Promise implementations • JQuery is a monad We are used to seeing custom names: • Promise(x).then(f) While in terms of algebraic functors they are defined generally • map(f, Promise(x))
  • 13. References • ramdajs • http://ramdajs.com/repl/?v=0.18.0 • auto curried functions • arguments arranged suitable for currying • fantasy-land • Algebraic JavaScript Specification • Lots of modules and libs • pointless-fantasy: a point-free implementation • ttps://github.com/douglascrockford/monad