Damian Łabas
Frontend Developer
Functional Programming in JS
Numer telefonu:
+48 788 266 229
Adres e-mail:
damian.labas@codibly.com
Meetup: JS dla zaawansowanych!
Autor: Damian Łabas
Functional Programming in JS
www.codibly.com
JavaScript
Procedural Programming
Object-Oriented Programming
Functional Programming
4
What is Functional Programming?
Imperative vs Declarative
In Imperative Programming, you write down how to do it.
In Declarative Programming, you write down what to do it.
6
What is in JS?
• First class functions
• Anonymous functions
• Closures
www.codibly.com
What is missing in JS?
• Recursion
• Immutability
• Purity
www.codibly.com
9
First class function
• They can by passed around
• They can be assigned to variables
• They can be stored in more complex data
structure, like array or objects
www.codibly.com
11
Closures
Closures - example
www.codibly.com
function grandParent (g1, g2) {
const g3 = 3;
return function parent (p1, p2) {
const p3 = 33;
return function child(c1, c2) {
const c3 = 333;
return g1 + g2 + g3 + p1 + p2 + p3 + c1 + c2 + c3
}
}
}
Closures - usage
www.codibly.com
const parentFunc = grandParent(1, 2); // return parent()
const childFunc = parentFunc(11, 22); // return child()
console.log(childFunc(111, 222)); // return 738
14
Recursion
Purity
Pure function - examples
www.codibly.com
function coin () {
return Math.random() < 0.5 ? 'heads' : 'tails'
}
let firstName = 'Damian';
function uppercaseName (lastName) {
return `${firstName.toUpperCase()} ${lastName.toUpperCase()}`
}
function calculatePrice (unitPrce, noOfUnits, couponValue = 0) {
return unitPrce * noOfUnits - couponValue;
}
17
Why pure function are better than impure?
Advantages of pure functions
• They are easier to read
• They are easier to test
• They can by more performant
www.codibly.com
19
20
Side Effects
• Modifying any external variable or object property
• Logging to the console
• Writing to file
• Call to API
www.codibly.com
22
Immutability
Immutability in JS
www.codibly.com
const freezeObject = Object.freeze({
foo: 'Hello',
bar: 'world',
baz: '!'
});
const freezeObject = Object.freeze({
foo: { greeting: 'Hello' },
bar: 'world',
baz: '!'
});
24
Higher-order Functions
Higher-order Functions either take functions as parameters, return functions
or both
Higher-order Function
• Abstract or isolate actions
• Async flow control using callback functions
• Promises
• Create utilities which can act on a wide variety
of data types
www.codibly.com
Higher-order Function - own map implementation
www.codibly.com
const arr1 = [1, 2, 3];
function mapForEach (arr, fn) {
const newArray = [];
for (let i = 0; i < arr.length; i++) {
newArray.push(fn(arr[i]))
}
return newArray;
}
const result = mapForEach(arr1,function (item) {
return item * 2
});
27
Function composition
Function composition - example
www.codibly.com
const users = [
{name: 'Damian', age: 23},
{name: 'Andrzej', age: 14},
{name: 'Dominika', age: 18}
];
const filter = (fn, arr) => arr.filter(fn);
const map = (fn, arr) => arr.map(fn);
map(user => user.name, filter(user => user.age >= 18)); // ['Damian,
'Dominika']
Higher-order function - compose and pipe
www.codibly.com
const compose = (...functions) => data =>
functions.reduceRight((value, fn) => fn(value), data);
const pipe = (...functions) => data =>
functions.reduce((value, fn) => fn(value), data);
30
Currying
Currying transforms a function into a sequence of functions each taking a
single argument of the function
Currying - example
www.codibly.com
function multiply (a, b, c) {
return a * b * c
}
function multiply (a) {
return function (b) {
return function (c) {
return a * b * c;
}
}
}
What is a partial application
or partial application function
33
What is a difference?
Is currying useful?
Partial application and currying - example
www.codibly.com
function discount (price, discount) {
return price * discount
}
function discount (discount) {
return function (price) {
return price * discount;
}
}
const tenPercentDiscunt = discount(0.1);
36
Questions?
Thank you
for your time!
www.codibly.com
/in/codibly
/codibly
/codibly
/codibly

Functional Programming In JS

  • 1.
    Damian Łabas Frontend Developer FunctionalProgramming in JS Numer telefonu: +48 788 266 229 Adres e-mail: damian.labas@codibly.com Meetup: JS dla zaawansowanych!
  • 2.
    Autor: Damian Łabas FunctionalProgramming in JS www.codibly.com
  • 3.
  • 4.
  • 5.
    Imperative vs Declarative InImperative Programming, you write down how to do it. In Declarative Programming, you write down what to do it.
  • 6.
  • 7.
    What is inJS? • First class functions • Anonymous functions • Closures www.codibly.com
  • 8.
    What is missingin JS? • Recursion • Immutability • Purity www.codibly.com
  • 9.
  • 10.
    First class function •They can by passed around • They can be assigned to variables • They can be stored in more complex data structure, like array or objects www.codibly.com
  • 11.
  • 12.
    Closures - example www.codibly.com functiongrandParent (g1, g2) { const g3 = 3; return function parent (p1, p2) { const p3 = 33; return function child(c1, c2) { const c3 = 333; return g1 + g2 + g3 + p1 + p2 + p3 + c1 + c2 + c3 } } }
  • 13.
    Closures - usage www.codibly.com constparentFunc = grandParent(1, 2); // return parent() const childFunc = parentFunc(11, 22); // return child() console.log(childFunc(111, 222)); // return 738
  • 14.
  • 15.
  • 16.
    Pure function -examples www.codibly.com function coin () { return Math.random() < 0.5 ? 'heads' : 'tails' } let firstName = 'Damian'; function uppercaseName (lastName) { return `${firstName.toUpperCase()} ${lastName.toUpperCase()}` } function calculatePrice (unitPrce, noOfUnits, couponValue = 0) { return unitPrce * noOfUnits - couponValue; }
  • 17.
    17 Why pure functionare better than impure?
  • 18.
    Advantages of purefunctions • They are easier to read • They are easier to test • They can by more performant www.codibly.com
  • 19.
  • 20.
  • 21.
    Side Effects • Modifyingany external variable or object property • Logging to the console • Writing to file • Call to API www.codibly.com
  • 22.
  • 23.
    Immutability in JS www.codibly.com constfreezeObject = Object.freeze({ foo: 'Hello', bar: 'world', baz: '!' }); const freezeObject = Object.freeze({ foo: { greeting: 'Hello' }, bar: 'world', baz: '!' });
  • 24.
    24 Higher-order Functions Higher-order Functionseither take functions as parameters, return functions or both
  • 25.
    Higher-order Function • Abstractor isolate actions • Async flow control using callback functions • Promises • Create utilities which can act on a wide variety of data types www.codibly.com
  • 26.
    Higher-order Function -own map implementation www.codibly.com const arr1 = [1, 2, 3]; function mapForEach (arr, fn) { const newArray = []; for (let i = 0; i < arr.length; i++) { newArray.push(fn(arr[i])) } return newArray; } const result = mapForEach(arr1,function (item) { return item * 2 });
  • 27.
  • 28.
    Function composition -example www.codibly.com const users = [ {name: 'Damian', age: 23}, {name: 'Andrzej', age: 14}, {name: 'Dominika', age: 18} ]; const filter = (fn, arr) => arr.filter(fn); const map = (fn, arr) => arr.map(fn); map(user => user.name, filter(user => user.age >= 18)); // ['Damian, 'Dominika']
  • 29.
    Higher-order function -compose and pipe www.codibly.com const compose = (...functions) => data => functions.reduceRight((value, fn) => fn(value), data); const pipe = (...functions) => data => functions.reduce((value, fn) => fn(value), data);
  • 30.
    30 Currying Currying transforms afunction into a sequence of functions each taking a single argument of the function
  • 31.
    Currying - example www.codibly.com functionmultiply (a, b, c) { return a * b * c } function multiply (a) { return function (b) { return function (c) { return a * b * c; } } }
  • 32.
    What is apartial application or partial application function
  • 33.
    33 What is adifference?
  • 34.
  • 35.
    Partial application andcurrying - example www.codibly.com function discount (price, discount) { return price * discount } function discount (discount) { return function (price) { return price * discount; } } const tenPercentDiscunt = discount(0.1);
  • 36.
  • 37.
    Thank you for yourtime! www.codibly.com /in/codibly /codibly /codibly /codibly