SlideShare a Scribd company logo
Fuel Up
JavaScript (with)
Functional
Programming
FAYA:80
About Me
 A passionate programmer finding my way around Functional
Programming…
 Work at UST Global
 I occasionally blog at http://stoi.wordpress.com
 Author of YieldJS & SlangJS
 I recently co-authored a book with my colleague, friend and
mentor called “.NET Design Patterns” by PACKT
Publishing
History
Logic
Computation
Category
Theory
David
Hilbert
Kurt
Godel
Gentzen
Alonzo
Church
Alan
Turing
Haskell
Curry
William
Howard
Leap ( A projectile at 90 degrees)
Computing Paradigm
 <Functional>
 Imperative Paradigms with OOP
 Domain Driven Design
 Design Patterns
 Object Functional
 Reactive Programming
 <Functional> Reactive
Computing Platform
 Single Core
 Multi-core
 Many-core
 Clusters/Load-Balancers
 Hypervisors
 Virtual Machines
 Cloud 100 Years
JS Evolution (A snap-shot)
Client Side
 DHTML/Dom Manipulation
 XMLHTTP/AJAX
 jQuery (John Resig)
 Web Frameworks
 YUI, JQuery UI, Backbone, Knockout,
Angular, Bootstrap etc.
 Libraries
 RxJs, Underscore, Prototype, Immutable,
Redux, Lodash, Ramda etc.
 Trans-compilers
 Coffescript, Typescript, Flow etc.
 Mobile Application Platforms
 Hybrid – Sencha/Cordova based
Server Side
 Node.js (Ryan Dahl)
 Node Modules
 JS Libraries
Being Functional
Algorithm composition to be dealt on the same lines
as mathematical function evaluations
 Referential Transparency
 Predictable
 Transparent
 Declarative
 Composable
 Modular
Lambda (λ) calculus
Alonzo Church Definition
Lambda calculus (also written as λ-calculus) is a
formal system in mathematical logic for expressing
computation based on function abstraction and
application using variable binding and substitution
var AddOperation = (x, y) => x + y;
Lambda Abstraction : λx.x+y [f(x,y) = x + y]
Variables : x & y
Lambda Term : x + y
Simplifications
1. Anonymous functions
2. Uses functions of a single input
Lambda (λ) calculus - Continued
 The following three rules give an inductive definition that can be applied
to build all syntactically valid lambda terms:
 A variable x, is itself a valid lambda term
 If t is a lambda term, and x is a variable, then (λx.t) is a lambda term (called a
lambda abstraction);
 if t and s are lambda terms, then (ts) is a lambda term (called an application)
Lambda (λ) calculus - Consequences
λ
Referential
Transparency
Anonymous
Functions
First-Class
Functions
Higher-Order
Functions
Closures
Currying &
Partial
Application
Recursion
Memoization
Referential Transparency
Code Motivation
Now since state of i is not guaranteed mutation-free
AddOneRO (x) <> AddOneRO (y)
if x = y, this further implies
AddOneRO (x) - AddOneRO (x) <> 0
thus invalidating the fundamental mathematical
identity
x – x = 0
Closures
Code Motivation
Now since state of i is not guaranteed mutation-free
AddOneRO (x) <> AddOneRO (y)
if x = y, this further implies
AddOneRO (x) - AddOneRO (x) <> 0
thus invalidating the fundamental mathematical
identity
x – x = 0
Currying Concept
 Transforms a function that takes
multiple arguments into a
chain of functions each with a
singleargument. a
f (a,b,c)
a
b
c
Currying Implementation – ES5
Augmenting Types Closures Apply Invocation
Currying Implementation – ES6
Closures Apply Invocation
Partial Application – ES6
Transforms a function that take multiple
arguments into afunction that accepts a
fixed number of arguments,
which in turn yields yet another
function that accepts the
remaining arguments.
Recursion
 Recursions are leveraged in functional
programming to accomplish
iteration/looping.
 Recursive functions invoke
themselves, performing an operation
repeatedly till the base case is reached
 Recursion typically involves adding
stack frames to the call stack, thus
growing the stack
 You can run out of stack space during
deep recursions
Tail-Call Optimization
 In this case, no state, except for the
calling function's address, needs to be
saved either on the stack or on the
heap
 Call stack frame for fIterator is reused
for storage of the intermediate results.
 Another thing to note is the addition
of an accumulator argument (product
in this case)
Monads
 Monad is a design pattern used to
describe computations as a series of
steps.
 Monads wrap types giving them
additional behavior like the automatic
propagation of empty value (Maybe
monad) or simplifying asynchronous
code (Continuation monad).
 Identity Monad
 Wraps Itself
 Maybe Monad
 It can represent the absence of any
value
 List Monad
 Represents a lazily computed list of
values
 Continuation monad
 Binds the context
JS Language Features That Aid
Functional Programming
ES5
 First-class functions
 Function objects
 Lexical scoping
 Function scope
 Closures
 Prototypal Inheritance
 Augmenting Types
 Function Invocation
 Controlling context (with Apply & Call)
 Array Methods
 map, reduce, filter
ES6
 Arrow Functions
 function*
 yield, yield* expressions
 Map object
Scenario1
 How do you add Exception Handling
to your code-base without
extensive code-change?
Scenario2
 You tend to write algorithms that
operate more often on a sequence of
items than on a single item.
 More likely, you’ll perform several
transformations between the source
collection and the ultimate result.
Scenario2 – Solution A
 Iterating the collection once for every
transformation (n iterations for n
transformations)
 Increases the execution time for
algorithms with many transformations
 Increases the application’s memory
footprint as it creates interim
collections for very transformation
END
Output List -> Interim List2
Transformation2 (Square)
Interim List2 -> [1, 9, 25]
Transformation1 (Filter Odds)
Interim List1 -> [1, 3, 5]
START
Input List -> [1, 2, 3, 4, 5]
Scenario2 – Solution B
 Create one method that processes
every transformation (1 iteration for n
transformations)
 Final Collection is produced in one
iteration. This improves performance
 Lowers the application’s memory
footprint as it doesn’t create interim
collections for every transformation
 Sacrifices Reusability (of individual
transformations)
END
Output List -> Interim List1
Transformation1 (Filter Odds + Square)
Interim List1 -> [1, 9, 25]
START
Input List -> [1, 2, 3, 4, 5]
Scenario2 – Solution C
 Iterators
 Enables you to create methods that operate on a sequence
 Iterator methods do not need to allocate storage for the entire sequence of
elements
 Process and return each element as it is requested (Deferred Execution)
Step in
 A JavaScript library for creating
Iterators, Generators and Continuation
methods for Arrays.
 The Iterator would be a method
getIterator() that augments the Array
data type and would have the
following interfaces:
 moveNext (method)
 current (property)
 reset (method)
ITERATOR
• Input List [1,2,3,4,5]
MoveNEXT
• 1 <- Square(FilterODD(1))-> OutputList [1]
MoveNEXT
• 2 <- FilterODD(2)-> MoveNEXT
• 3 <- Square(FilterODD(3))-> OutputList [1,9]
MoveNEXT
• 4 <- FilterODD(4)-> MoveNEXT
• 5 <- Square(FilterODD(5))-> OutputList [1,9,25]
ES6 – Generators & Iterators
 function*
 The function* declaration (function
keyword followed by an asterisk)
defines a generator function, which
returns a Generator object.
 Generator Object
 The Generator object is returned by a
generator function and it conforms to
both the iterable protocol and the
iterator protocol.
 Generators are functions which can be
exited and later re-entered. Their
context (variable bindings) will be
saved across re-entrances.
Concluding
 The proof is in the pudding!!!

More Related Content

What's hot

Pattern Matching - at a glance
Pattern Matching - at a glancePattern Matching - at a glance
Pattern Matching - at a glance
Knoldus Inc.
 
A Survey of Concurrency Constructs
A Survey of Concurrency ConstructsA Survey of Concurrency Constructs
A Survey of Concurrency Constructs
Ted Leung
 
Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With Scala
Xebia IT Architects
 
Java 103 intro to java data structures
Java 103   intro to java data structuresJava 103   intro to java data structures
Java 103 intro to java data structures
agorolabs
 
1 list datastructures
1 list datastructures1 list datastructures
1 list datastructures
Nguync91368
 
Introduction To R Language
Introduction To R LanguageIntroduction To R Language
Introduction To R Language
Gaurang Dobariya
 
Functional Programming in Scala: Notes
Functional Programming in Scala: NotesFunctional Programming in Scala: Notes
Functional Programming in Scala: Notes
Roberto Casadei
 
Core java concepts
Core java conceptsCore java concepts
Core java concepts
laratechnologies
 
Introduction à Scala - Michel Schinz - January 2010
Introduction à Scala - Michel Schinz - January 2010Introduction à Scala - Michel Schinz - January 2010
Introduction à Scala - Michel Schinz - January 2010
JUG Lausanne
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdfHiroshi Ono
 
Introduction to matlab
Introduction to matlabIntroduction to matlab
Introduction to matlab
Khulna University
 
Arrays in Data Structure and Algorithm
Arrays in Data Structure and Algorithm Arrays in Data Structure and Algorithm
Arrays in Data Structure and Algorithm
KristinaBorooah
 
stacks and queues for public
stacks and queues for publicstacks and queues for public
stacks and queues for public
iqbalphy1
 
C++ Standard Template Library
C++ Standard Template LibraryC++ Standard Template Library
C++ Standard Template Library
Ilio Catallo
 
Functors, Applicatives and Monads In Scala
Functors, Applicatives and Monads In ScalaFunctors, Applicatives and Monads In Scala
Functors, Applicatives and Monads In Scala
Knoldus Inc.
 
Functional programming with Scala
Functional programming with ScalaFunctional programming with Scala
Functional programming with Scala
Neelkanth Sachdeva
 
Cupdf.com introduction to-data-structures-and-algorithm
Cupdf.com introduction to-data-structures-and-algorithmCupdf.com introduction to-data-structures-and-algorithm
Cupdf.com introduction to-data-structures-and-algorithm
TarikuDabala1
 

What's hot (20)

Pattern Matching - at a glance
Pattern Matching - at a glancePattern Matching - at a glance
Pattern Matching - at a glance
 
A Survey of Concurrency Constructs
A Survey of Concurrency ConstructsA Survey of Concurrency Constructs
A Survey of Concurrency Constructs
 
Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With Scala
 
Java 103 intro to java data structures
Java 103   intro to java data structuresJava 103   intro to java data structures
Java 103 intro to java data structures
 
camel-scala.pdf
camel-scala.pdfcamel-scala.pdf
camel-scala.pdf
 
1 list datastructures
1 list datastructures1 list datastructures
1 list datastructures
 
Introduction To R Language
Introduction To R LanguageIntroduction To R Language
Introduction To R Language
 
Functional Programming in Scala: Notes
Functional Programming in Scala: NotesFunctional Programming in Scala: Notes
Functional Programming in Scala: Notes
 
Core java concepts
Core java conceptsCore java concepts
Core java concepts
 
Introduction à Scala - Michel Schinz - January 2010
Introduction à Scala - Michel Schinz - January 2010Introduction à Scala - Michel Schinz - January 2010
Introduction à Scala - Michel Schinz - January 2010
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
 
Introduction to matlab
Introduction to matlabIntroduction to matlab
Introduction to matlab
 
Matlab1
Matlab1Matlab1
Matlab1
 
Arrays in Data Structure and Algorithm
Arrays in Data Structure and Algorithm Arrays in Data Structure and Algorithm
Arrays in Data Structure and Algorithm
 
stacks and queues for public
stacks and queues for publicstacks and queues for public
stacks and queues for public
 
C++ Standard Template Library
C++ Standard Template LibraryC++ Standard Template Library
C++ Standard Template Library
 
Scala
ScalaScala
Scala
 
Functors, Applicatives and Monads In Scala
Functors, Applicatives and Monads In ScalaFunctors, Applicatives and Monads In Scala
Functors, Applicatives and Monads In Scala
 
Functional programming with Scala
Functional programming with ScalaFunctional programming with Scala
Functional programming with Scala
 
Cupdf.com introduction to-data-structures-and-algorithm
Cupdf.com introduction to-data-structures-and-algorithmCupdf.com introduction to-data-structures-and-algorithm
Cupdf.com introduction to-data-structures-and-algorithm
 

Similar to Fuel Up JavaScript with Functional Programming

Scala for Machine Learning
Scala for Machine LearningScala for Machine Learning
Scala for Machine Learning
Patrick Nicolas
 
Concurrency Constructs Overview
Concurrency Constructs OverviewConcurrency Constructs Overview
Concurrency Constructs Overview
stasimus
 
Евгений Бурмако «scala.reflect»
Евгений Бурмако «scala.reflect»Евгений Бурмако «scala.reflect»
Евгений Бурмако «scala.reflect»
e-Legion
 
scala.reflect, Eugene Burmako
scala.reflect, Eugene Burmakoscala.reflect, Eugene Burmako
scala.reflect, Eugene Burmako
Vasil Remeniuk
 
Short intro to scala and the play framework
Short intro to scala and the play frameworkShort intro to scala and the play framework
Short intro to scala and the play framework
Felipe
 
Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009
Martin Odersky
 
Java8: what's new and what's hot
Java8: what's new and what's hotJava8: what's new and what's hot
Java8: what's new and what's hot
Sergii Maliarov
 
Functional Programming With Scala
Functional Programming With ScalaFunctional Programming With Scala
Functional Programming With Scala
Knoldus Inc.
 
Charles Sharp: Java 8 Streams
Charles Sharp: Java 8 StreamsCharles Sharp: Java 8 Streams
Charles Sharp: Java 8 Streams
jessitron
 
Java 8 lambda
Java 8 lambdaJava 8 lambda
Java 8 lambda
Manav Prasad
 
10-DesignPatterns.ppt
10-DesignPatterns.ppt10-DesignPatterns.ppt
10-DesignPatterns.ppt
TAGADPALLEWARPARTHVA
 
Automatic Task-based Code Generation for High Performance DSEL
Automatic Task-based Code Generation for High Performance DSELAutomatic Task-based Code Generation for High Performance DSEL
Automatic Task-based Code Generation for High Performance DSEL
Joel Falcou
 
ScalaDays 2013 Keynote Speech by Martin Odersky
ScalaDays 2013 Keynote Speech by Martin OderskyScalaDays 2013 Keynote Speech by Martin Odersky
ScalaDays 2013 Keynote Speech by Martin Odersky
Typesafe
 
PythonStudyMaterialSTudyMaterial.pdf
PythonStudyMaterialSTudyMaterial.pdfPythonStudyMaterialSTudyMaterial.pdf
PythonStudyMaterialSTudyMaterial.pdf
data2businessinsight
 
Introduction to new features in java 8
Introduction to new features in java 8Introduction to new features in java 8
Introduction to new features in java 8
Introduction to new features in java 8Introduction to new features in java 8
Introduction to new features in java 8
Raffi Khatchadourian
 
Patterns in Python
Patterns in PythonPatterns in Python
Patterns in Python
dn
 
Scala clojure techday_2011
Scala clojure techday_2011Scala clojure techday_2011
Scala clojure techday_2011
Thadeu Russo
 

Similar to Fuel Up JavaScript with Functional Programming (20)

Scala for Machine Learning
Scala for Machine LearningScala for Machine Learning
Scala for Machine Learning
 
Concurrency Constructs Overview
Concurrency Constructs OverviewConcurrency Constructs Overview
Concurrency Constructs Overview
 
Евгений Бурмако «scala.reflect»
Евгений Бурмако «scala.reflect»Евгений Бурмако «scala.reflect»
Евгений Бурмако «scala.reflect»
 
scala.reflect, Eugene Burmako
scala.reflect, Eugene Burmakoscala.reflect, Eugene Burmako
scala.reflect, Eugene Burmako
 
Short intro to scala and the play framework
Short intro to scala and the play frameworkShort intro to scala and the play framework
Short intro to scala and the play framework
 
Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009
 
Clojure intro
Clojure introClojure intro
Clojure intro
 
Java8: what's new and what's hot
Java8: what's new and what's hotJava8: what's new and what's hot
Java8: what's new and what's hot
 
Functional Programming With Scala
Functional Programming With ScalaFunctional Programming With Scala
Functional Programming With Scala
 
Charles Sharp: Java 8 Streams
Charles Sharp: Java 8 StreamsCharles Sharp: Java 8 Streams
Charles Sharp: Java 8 Streams
 
Java 8 lambda
Java 8 lambdaJava 8 lambda
Java 8 lambda
 
10-DesignPatterns.ppt
10-DesignPatterns.ppt10-DesignPatterns.ppt
10-DesignPatterns.ppt
 
Automatic Task-based Code Generation for High Performance DSEL
Automatic Task-based Code Generation for High Performance DSELAutomatic Task-based Code Generation for High Performance DSEL
Automatic Task-based Code Generation for High Performance DSEL
 
Oct.22nd.Presentation.Final
Oct.22nd.Presentation.FinalOct.22nd.Presentation.Final
Oct.22nd.Presentation.Final
 
ScalaDays 2013 Keynote Speech by Martin Odersky
ScalaDays 2013 Keynote Speech by Martin OderskyScalaDays 2013 Keynote Speech by Martin Odersky
ScalaDays 2013 Keynote Speech by Martin Odersky
 
PythonStudyMaterialSTudyMaterial.pdf
PythonStudyMaterialSTudyMaterial.pdfPythonStudyMaterialSTudyMaterial.pdf
PythonStudyMaterialSTudyMaterial.pdf
 
Introduction to new features in java 8
Introduction to new features in java 8Introduction to new features in java 8
Introduction to new features in java 8
 
Introduction to new features in java 8
Introduction to new features in java 8Introduction to new features in java 8
Introduction to new features in java 8
 
Patterns in Python
Patterns in PythonPatterns in Python
Patterns in Python
 
Scala clojure techday_2011
Scala clojure techday_2011Scala clojure techday_2011
Scala clojure techday_2011
 

Recently uploaded

Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Shahin Sheidaei
 
Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604
Fermin Galan
 
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Globus
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
Matt Welsh
 
Enterprise Resource Planning System in Telangana
Enterprise Resource Planning System in TelanganaEnterprise Resource Planning System in Telangana
Enterprise Resource Planning System in Telangana
NYGGS Automation Suite
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
abdulrafaychaudhry
 
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdfDominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
AMB-Review
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Globus
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar
 
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
Paco van Beckhoven
 
Graphic Design Crash Course for beginners
Graphic Design Crash Course for beginnersGraphic Design Crash Course for beginners
Graphic Design Crash Course for beginners
e20449
 
How to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good PracticesHow to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good Practices
Globus
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
Globus
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
Georgi Kodinov
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
Globus
 
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Mind IT Systems
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
Ortus Solutions, Corp
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Globus
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
Max Andersen
 

Recently uploaded (20)

Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
 
Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604
 
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
 
Enterprise Resource Planning System in Telangana
Enterprise Resource Planning System in TelanganaEnterprise Resource Planning System in Telangana
Enterprise Resource Planning System in Telangana
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
 
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdfDominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
 
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
 
Graphic Design Crash Course for beginners
Graphic Design Crash Course for beginnersGraphic Design Crash Course for beginners
Graphic Design Crash Course for beginners
 
How to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good PracticesHow to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good Practices
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
 
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
 

Fuel Up JavaScript with Functional Programming

  • 2. About Me  A passionate programmer finding my way around Functional Programming…  Work at UST Global  I occasionally blog at http://stoi.wordpress.com  Author of YieldJS & SlangJS  I recently co-authored a book with my colleague, friend and mentor called “.NET Design Patterns” by PACKT Publishing
  • 4. Leap ( A projectile at 90 degrees) Computing Paradigm  <Functional>  Imperative Paradigms with OOP  Domain Driven Design  Design Patterns  Object Functional  Reactive Programming  <Functional> Reactive Computing Platform  Single Core  Multi-core  Many-core  Clusters/Load-Balancers  Hypervisors  Virtual Machines  Cloud 100 Years
  • 5. JS Evolution (A snap-shot) Client Side  DHTML/Dom Manipulation  XMLHTTP/AJAX  jQuery (John Resig)  Web Frameworks  YUI, JQuery UI, Backbone, Knockout, Angular, Bootstrap etc.  Libraries  RxJs, Underscore, Prototype, Immutable, Redux, Lodash, Ramda etc.  Trans-compilers  Coffescript, Typescript, Flow etc.  Mobile Application Platforms  Hybrid – Sencha/Cordova based Server Side  Node.js (Ryan Dahl)  Node Modules  JS Libraries
  • 6. Being Functional Algorithm composition to be dealt on the same lines as mathematical function evaluations  Referential Transparency  Predictable  Transparent  Declarative  Composable  Modular
  • 7. Lambda (λ) calculus Alonzo Church Definition Lambda calculus (also written as λ-calculus) is a formal system in mathematical logic for expressing computation based on function abstraction and application using variable binding and substitution var AddOperation = (x, y) => x + y; Lambda Abstraction : λx.x+y [f(x,y) = x + y] Variables : x & y Lambda Term : x + y Simplifications 1. Anonymous functions 2. Uses functions of a single input
  • 8. Lambda (λ) calculus - Continued  The following three rules give an inductive definition that can be applied to build all syntactically valid lambda terms:  A variable x, is itself a valid lambda term  If t is a lambda term, and x is a variable, then (λx.t) is a lambda term (called a lambda abstraction);  if t and s are lambda terms, then (ts) is a lambda term (called an application)
  • 9. Lambda (λ) calculus - Consequences λ Referential Transparency Anonymous Functions First-Class Functions Higher-Order Functions Closures Currying & Partial Application Recursion Memoization
  • 10. Referential Transparency Code Motivation Now since state of i is not guaranteed mutation-free AddOneRO (x) <> AddOneRO (y) if x = y, this further implies AddOneRO (x) - AddOneRO (x) <> 0 thus invalidating the fundamental mathematical identity x – x = 0
  • 11. Closures Code Motivation Now since state of i is not guaranteed mutation-free AddOneRO (x) <> AddOneRO (y) if x = y, this further implies AddOneRO (x) - AddOneRO (x) <> 0 thus invalidating the fundamental mathematical identity x – x = 0
  • 12. Currying Concept  Transforms a function that takes multiple arguments into a chain of functions each with a singleargument. a f (a,b,c) a b c
  • 13. Currying Implementation – ES5 Augmenting Types Closures Apply Invocation
  • 14. Currying Implementation – ES6 Closures Apply Invocation
  • 15. Partial Application – ES6 Transforms a function that take multiple arguments into afunction that accepts a fixed number of arguments, which in turn yields yet another function that accepts the remaining arguments.
  • 16. Recursion  Recursions are leveraged in functional programming to accomplish iteration/looping.  Recursive functions invoke themselves, performing an operation repeatedly till the base case is reached  Recursion typically involves adding stack frames to the call stack, thus growing the stack  You can run out of stack space during deep recursions
  • 17. Tail-Call Optimization  In this case, no state, except for the calling function's address, needs to be saved either on the stack or on the heap  Call stack frame for fIterator is reused for storage of the intermediate results.  Another thing to note is the addition of an accumulator argument (product in this case)
  • 18. Monads  Monad is a design pattern used to describe computations as a series of steps.  Monads wrap types giving them additional behavior like the automatic propagation of empty value (Maybe monad) or simplifying asynchronous code (Continuation monad).  Identity Monad  Wraps Itself  Maybe Monad  It can represent the absence of any value  List Monad  Represents a lazily computed list of values  Continuation monad  Binds the context
  • 19. JS Language Features That Aid Functional Programming ES5  First-class functions  Function objects  Lexical scoping  Function scope  Closures  Prototypal Inheritance  Augmenting Types  Function Invocation  Controlling context (with Apply & Call)  Array Methods  map, reduce, filter ES6  Arrow Functions  function*  yield, yield* expressions  Map object
  • 20. Scenario1  How do you add Exception Handling to your code-base without extensive code-change?
  • 21. Scenario2  You tend to write algorithms that operate more often on a sequence of items than on a single item.  More likely, you’ll perform several transformations between the source collection and the ultimate result.
  • 22. Scenario2 – Solution A  Iterating the collection once for every transformation (n iterations for n transformations)  Increases the execution time for algorithms with many transformations  Increases the application’s memory footprint as it creates interim collections for very transformation END Output List -> Interim List2 Transformation2 (Square) Interim List2 -> [1, 9, 25] Transformation1 (Filter Odds) Interim List1 -> [1, 3, 5] START Input List -> [1, 2, 3, 4, 5]
  • 23. Scenario2 – Solution B  Create one method that processes every transformation (1 iteration for n transformations)  Final Collection is produced in one iteration. This improves performance  Lowers the application’s memory footprint as it doesn’t create interim collections for every transformation  Sacrifices Reusability (of individual transformations) END Output List -> Interim List1 Transformation1 (Filter Odds + Square) Interim List1 -> [1, 9, 25] START Input List -> [1, 2, 3, 4, 5]
  • 24. Scenario2 – Solution C  Iterators  Enables you to create methods that operate on a sequence  Iterator methods do not need to allocate storage for the entire sequence of elements  Process and return each element as it is requested (Deferred Execution)
  • 25. Step in  A JavaScript library for creating Iterators, Generators and Continuation methods for Arrays.  The Iterator would be a method getIterator() that augments the Array data type and would have the following interfaces:  moveNext (method)  current (property)  reset (method) ITERATOR • Input List [1,2,3,4,5] MoveNEXT • 1 <- Square(FilterODD(1))-> OutputList [1] MoveNEXT • 2 <- FilterODD(2)-> MoveNEXT • 3 <- Square(FilterODD(3))-> OutputList [1,9] MoveNEXT • 4 <- FilterODD(4)-> MoveNEXT • 5 <- Square(FilterODD(5))-> OutputList [1,9,25]
  • 26. ES6 – Generators & Iterators  function*  The function* declaration (function keyword followed by an asterisk) defines a generator function, which returns a Generator object.  Generator Object  The Generator object is returned by a generator function and it conforms to both the iterable protocol and the iterator protocol.  Generators are functions which can be exited and later re-entered. Their context (variable bindings) will be saved across re-entrances.
  • 27. Concluding  The proof is in the pudding!!!

Editor's Notes

  1. Output of these functions would purely depend on the inputs provided Moreover, any applicable data structures that the algorithm would need to create the output would be transient, having a lifetime within the function scope, and thus help in avoiding state mutation