SlideShare a Scribd company logo
Func up your code
Maciej Komorowski
What is func%onal programming?
Func%onal programming is
programming paradigm [...] that
treats computa%on as the evalua%on
of mathema&cal func&ons and
avoids changing-state and mutable
data.
— Wikipedia
Pillars of FP
• Higher-order func0ons (e.g. map)
• Immutable data
• Lazy evalua0on
• Pure func0ons
• Recursion
Pure func)on
! Always evaluates the same result value given the same
arguments
! Does not cause any seman5cally observable side effect, such as
muta5on of mutable objects
Pure func)on examples
// Pure
function add(a, b) {
return a + b;
}
// Impure
Math.random();
// Impure
const items = []
function addItem(item) {
return items.push(item);
}
State muta(on
State muta(on in OOP
! Relies heavily on encapsula)on
! Has hidden nature
! Brings nondeterminism
! Root cause of doom
Brogrammer1
State muta)on example
A brogrammer is [...] a slang term for a
macho, male programmer. A brogrammer
might self-describe as a sociable
programmer.
— Wikipedia
1
Frans Hals, Oil on canvas, 1630. Source: classicprogrammerpain;ngs
What brogrammer does?
• drinkBeer
• talk
Stateful implementa*on
class Brogrammer {
constructor() {
this.beers = 0;
}
drinkBeer() { /* ... */ }
talk() { /* ... */ }
}
Stateful – drinkBeer
it('increment number of drunk beers', () => {
expect(brogrammer.drinkBeer()).toEqual(1);
expect(brogrammer.drinkBeer()).toEqual(2);
});
// Inside Brogrammer class
drinkBeer() {
return this.beers += 1; // encapsulates 'beers'
}
Stateful – talk tests
it('says "Beer me up!" before drinking', () => {
expect(brogrammer.talk()).toEqual("Beer me up!");
});
it('says "Yummy" after 1st beer', () => {
brogrammer.drinkBeer();
expect(brogrammer.talk()).toEqual("Yummy");
});
it('says "I a<M dRuNk" after 10th beer', () => {
brogrammer.drinkBeer();
// 8 x brogrammer.drinkBeer();
brogrammer.drinkBeer();
expect(brogrammer.talk()).toEqual("I a<M dRuNk");
});
Stateful – talk implementa+on
// Inside Brogrammer class
talk() {
return ({
0: 'Beer me up!',
1: 'Yummy',
// ...
10: 'I a<M dRuNk',
})[this.beers] || '';
}
How to remove state?
Single source of truth
Naïve stateless – implementa+on
class Brogrammer {
constructor(store) {
this.store = store;
}
// ...
}
Naïve stateless – drinkBeer tests
it('increment number of drunk beers', () => {
const store = { beers: 0 };
const brogrammer = new Brogrammer(store);
brogrammer.drinkBeer();
expect(store.beers).toEqual(1);
});
Naïve stateless – drinkBeer implementa+on
// Inside Brogrammer class
drinkBeer() {
return this.store.beers += 1;
}
Naïve stateless – talk tests
it('says "I a<M dRuNk" after 10th beer', () => {
const store = { beers: 10 };
const brogrammer = new Brogrammer(store);
expect(brogrammer.talk()).toEqual("I a<M dRuNk");
});
Naïve stateless – talk implementa+on
// Inside Brogrammer class
talk() {
return ({
0: 'Beer me up!',
1: 'Yummy',
// ...
10: 'I a<M dRuNk',
})[this.store.beers] || '';
}
Solu%on review
! Removed state from the Brogrammer
! Easier tes2ng
" Lost encapsula-on
How to improve?
The Redux way
Redux workflow2
2
Source: CSS-Tricks
Three Principles of Redux3
! Single source of truth
! State is read-only
! Changes are made with pure func)ons
3
Source: Redux
Three Principles of Redux
Single source of truth
console.log(store.getState());
// {
// brogrammer: {
// beers: 0
// }
// }
Three Principles of Redux
State is read-only
store.dispatch({
type: 'INCREMENT_BEERS',
});
Three Principles of Redux
Changes are made with pure func3ons
function brogrammer(state = {}, action) {
switch (action.type) {
case 'SET_BEERS':
return {
...state,
beers: 5,
};
// case ...
}
}
Redux – incrementBeers ac%on
it('returns action with type INCREMENT_BEERS', () => {
const action = incrementBeers();
expect(action).toEqual({
type: 'INCREMENT_BEERS'
});
});
Redux – incrementBeers ac%on
const incrementBeers = () => ({
type: 'INCREMENT_BEERS',
});
Redux – brogrammer reducer
it('returns state with incremented beers', () => {
const state = { beers: 0 };
const action = incrementBeers();
const nextState = brogrammer(state, action);
expect(nextState).toEqual({ beers: 1 });
});
Redux – brogrammer reducer
implementa)on
const brogrammer = (state = {}, action) => {
switch (action.type) {
case 'INCREMENT_BEERS':
return {
...state,
beers: state.beers + 1
};
default:
return state
}
}
Redux – drinkBeer tests
it('increment number of drunk beers', () => {
const store = createStore({ beers: 0 });
const brogrammer = new Brogrammer(store);
brogrammer.drinkBeer();
expect(store.dispatch)
.toHaveBeenCalledWith(incrementBeers());
});
Redux – drinkBeer implementa+on
// Inside Brogrammer class
drinkBeer() {
return this.store.dispatch(incrementBeers());
}
Redux – talk tests
it('says "I a<M dRuNk" after 10th beer', () => {
const store = createStore({ beers: 10 });
const brogrammer = new Brogrammer(store);
expect(brogrammer.talk()).toEqual("I a<M dRuNk");
});
Redux – talk implementa+on
// Inside Brogrammer class
talk() {
return ({
0: 'Beer me up!',
1: 'Yummy',
// ...
10: 'I a<M dRuNk',
})[this.store.get('beers')] || '';
}
Solu%on review
! Easy tes(ng
! Be,er separa(on
! Explicit state changes
! Full control over state
A few thoughts on Redux
Immutable data
Mutable vs immutable
// Mutable
const items = ['foo'];
items.push('bar');
items.push('baz');
console.log(items); // ["foo", "bar", "baz"]
Mutable vs immutable
// Immutable via immutable-js
const items = Immutable.List.of('foo');
items.push('bar');
items.push('baz');
console.log(items.toArray());
// ["foo"]
console.log(items.push('bar').push('baz').toArray());
// ["foo", "bar", "baz"]
What about performance?5
5
Source: React.js Conf 2015 - Immutable Data and React
Performance benchmark
Array push 1,000,000 items:
var list = [];
for (var i = 0; i < 1000000; i++) {
list.push(i);
}
83 ms
Performance benchmark
Mori immutable vector conj 1,000,000 items:
var list = mori.vector();
for (var i = 0; i < 1000000; i++) {
mori.conj(list, i);
}
288 ms
Should update problem
const form = { /* ... */ };
function submit(form) {
if (hasChanged(form)) {
doSomethingExpensive(form);
}
}
Should update problem
versioning
let currentFormVersion;
function hasChanged(form) {
const formVersion = md5(JSON.stringify(form));
return formVersion !== currentFormVersion;
}
Should update problem
dirty bits
function hasChanged(form) {
for (var field in form) {
if (field.meta.dirty === true) {
return true;
}
}
return false;
}
Should update problem
observable pa+ern
const form = { /* ... */ };
Object.observe(form, changes => {
doSomethingExpensive(form);
});
form.firstName = 'Maciej';
form.lastName = 'Komorowski';
form.profession = 'Brogrammer'; // Not true :)
Should update problem
immutable
let currentForm = { /* ... */ };
function hasChanged(form) {
return currentForm !== form;
}
Memoiza(on example
function memoize(fn) {
var cache = {};
return function (arg) {
var hash = arg === Object(arg)
? JSON.stringify(arg) // Wat?
: arg;
return hash in cache ?
cache[hash] :
(cache[hash] = fn.call(this, arg));
}
}
Memoiza(on example
function rawSum(list) {
return list.reduce((a, b) => a + b)
}
const sum = memoize(rawSum);
const array = [0, 1, ...1000000];
sum(array); // 89 ms
rawSum(array); // 51 ms
sum(array); // 42 ms
Advantages of immutability
! No defensive copies
! Can be faster
! Be3er for concurrency (no deadlocks)
Explore func-onal programing❗
It's worth it
Contact
Maciej Komorowski
@komomc
Quiz
What f does?
f = 0 : 1 : zipWith (+) f (tail f)
Answer
Generates Fibonacci sequence
> let fibs = 0 : 1 : zipWith (+) fibs (tail fibs)
> take 11 fibs
[0,1,1,2,3,5,8,13,21,34,55]

More Related Content

PDF
Asynchronous JS in Odoo
DOCX
VISUALIZAR REGISTROS EN UN JTABLE
PDF
What's up with Prototype and script.aculo.us?
PPTX
Performance Optimization In Angular 2
PDF
Clojure functions examples
PPTX
Template syntax in Angular 2.0
PPTX
Angular 2 Architecture
PPTX
Angular 2.0 Pipes
Asynchronous JS in Odoo
VISUALIZAR REGISTROS EN UN JTABLE
What's up with Prototype and script.aculo.us?
Performance Optimization In Angular 2
Clojure functions examples
Template syntax in Angular 2.0
Angular 2 Architecture
Angular 2.0 Pipes

What's hot (20)

PDF
Javascript & Ajax Basics
PPT
Lecture04
PPT
Class ‘increment’
PPTX
Http Communication in Angular 2.0
PDF
How to Create a l10n Payroll Structure
PDF
Symfony World - Symfony components and design patterns
PDF
G*ワークショップ in 仙台 Grails(とことん)入門
PDF
Dutch php a short tale about state machine
DOCX
exportDisabledUsersRemoveMailbox
PDF
Relay Modern: architecture and workflow
PDF
Angular promises and http
PDF
05 communications
PDF
Protocol-Oriented MVVM
PDF
PDF
Angular server-side communication
PDF
Impact of the New ORM on Your Modules
PPTX
Angular 2.0 forms
PDF
Cocoa heads 09112017
PDF
Berlin meetup
PPTX
Component lifecycle hooks in Angular 2.0
Javascript & Ajax Basics
Lecture04
Class ‘increment’
Http Communication in Angular 2.0
How to Create a l10n Payroll Structure
Symfony World - Symfony components and design patterns
G*ワークショップ in 仙台 Grails(とことん)入門
Dutch php a short tale about state machine
exportDisabledUsersRemoveMailbox
Relay Modern: architecture and workflow
Angular promises and http
05 communications
Protocol-Oriented MVVM
Angular server-side communication
Impact of the New ORM on Your Modules
Angular 2.0 forms
Cocoa heads 09112017
Berlin meetup
Component lifecycle hooks in Angular 2.0
Ad

Viewers also liked (16)

DOCX
ThesisProposal
PDF
علت نیاز به وب سایت
PPTX
День банкира
PDF
Visual Media Portfolio
PDF
Gdz 11 klas_geometrija_o_v_pogorelov
PDF
Star software marketing plan
PPTX
Onderwijs binnen inclusieve samenleving koca
PDF
Harrypotty preview
PDF
Rae Aspectos Morfologicos de la Lengua
PDF
We aim to cheese - LB
PDF
13APortfolioKeestanWilles
PDF
IMD MBA Class Profiles
PDF
Газпром-нефть
PPT
IngléS
PDF
Content Marketing: Your Digital Salesperson
PDF
Final task Unit 5
ThesisProposal
علت نیاز به وب سایت
День банкира
Visual Media Portfolio
Gdz 11 klas_geometrija_o_v_pogorelov
Star software marketing plan
Onderwijs binnen inclusieve samenleving koca
Harrypotty preview
Rae Aspectos Morfologicos de la Lengua
We aim to cheese - LB
13APortfolioKeestanWilles
IMD MBA Class Profiles
Газпром-нефть
IngléS
Content Marketing: Your Digital Salesperson
Final task Unit 5
Ad

Similar to Func up your code (20)

PDF
Building Functional Islands
PDF
379008-rc217-functionalprogramming
PPTX
A Skeptics guide to functional style javascript
PPTX
Functional programming with Immutable .JS
PPTX
Functional programming in javascript
PDF
Functional Programming
PDF
Introduction to Functional Programming
PDF
Predictable reactive state management - ngrx
PPTX
Thinking Functionally with JavaScript
ODP
Functional programming
PDF
Functional Programming with JavaScript
PDF
Functional JS for everyone - 4Developers
PDF
Intro to functional programming - Confoo
PPTX
Functional Programming in Javascript - IL Tech Talks week
PDF
React JS & Functional Programming Principles
PPTX
Functional Programming in JavaScript by Luis Atencio
PDF
Esta charla es una monada - Introducción a FP en JavaScript con Ramda
PPTX
Things about Functional JavaScript
PDF
Reactive Programming with JavaScript
PDF
2018 02-22 React, Redux & Building Applications that Scale | Redux
Building Functional Islands
379008-rc217-functionalprogramming
A Skeptics guide to functional style javascript
Functional programming with Immutable .JS
Functional programming in javascript
Functional Programming
Introduction to Functional Programming
Predictable reactive state management - ngrx
Thinking Functionally with JavaScript
Functional programming
Functional Programming with JavaScript
Functional JS for everyone - 4Developers
Intro to functional programming - Confoo
Functional Programming in Javascript - IL Tech Talks week
React JS & Functional Programming Principles
Functional Programming in JavaScript by Luis Atencio
Esta charla es una monada - Introducción a FP en JavaScript con Ramda
Things about Functional JavaScript
Reactive Programming with JavaScript
2018 02-22 React, Redux & Building Applications that Scale | Redux

Recently uploaded (20)

PPTX
Transform Your Business with a Software ERP System
PPTX
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
PPTX
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
PDF
Adobe Premiere Pro 2025 (v24.5.0.057) Crack free
PPTX
Essential Infomation Tech presentation.pptx
PDF
Adobe Illustrator 28.6 Crack My Vision of Vector Design
PDF
wealthsignaloriginal-com-DS-text-... (1).pdf
PDF
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf
PDF
Odoo Companies in India – Driving Business Transformation.pdf
PPTX
L1 - Introduction to python Backend.pptx
PDF
Audit Checklist Design Aligning with ISO, IATF, and Industry Standards — Omne...
PPTX
CHAPTER 2 - PM Management and IT Context
PDF
Softaken Excel to vCard Converter Software.pdf
PDF
Design an Analysis of Algorithms I-SECS-1021-03
PDF
Upgrade and Innovation Strategies for SAP ERP Customers
PDF
System and Network Administration Chapter 2
PDF
PTS Company Brochure 2025 (1).pdf.......
PDF
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
PPTX
VVF-Customer-Presentation2025-Ver1.9.pptx
PDF
medical staffing services at VALiNTRY
Transform Your Business with a Software ERP System
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
Adobe Premiere Pro 2025 (v24.5.0.057) Crack free
Essential Infomation Tech presentation.pptx
Adobe Illustrator 28.6 Crack My Vision of Vector Design
wealthsignaloriginal-com-DS-text-... (1).pdf
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf
Odoo Companies in India – Driving Business Transformation.pdf
L1 - Introduction to python Backend.pptx
Audit Checklist Design Aligning with ISO, IATF, and Industry Standards — Omne...
CHAPTER 2 - PM Management and IT Context
Softaken Excel to vCard Converter Software.pdf
Design an Analysis of Algorithms I-SECS-1021-03
Upgrade and Innovation Strategies for SAP ERP Customers
System and Network Administration Chapter 2
PTS Company Brochure 2025 (1).pdf.......
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
VVF-Customer-Presentation2025-Ver1.9.pptx
medical staffing services at VALiNTRY

Func up your code

  • 1. Func up your code Maciej Komorowski
  • 2. What is func%onal programming?
  • 3. Func%onal programming is programming paradigm [...] that treats computa%on as the evalua%on of mathema&cal func&ons and avoids changing-state and mutable data. — Wikipedia
  • 4. Pillars of FP • Higher-order func0ons (e.g. map) • Immutable data • Lazy evalua0on • Pure func0ons • Recursion
  • 5. Pure func)on ! Always evaluates the same result value given the same arguments ! Does not cause any seman5cally observable side effect, such as muta5on of mutable objects
  • 6. Pure func)on examples // Pure function add(a, b) { return a + b; } // Impure Math.random(); // Impure const items = [] function addItem(item) { return items.push(item); }
  • 8. State muta(on in OOP ! Relies heavily on encapsula)on ! Has hidden nature ! Brings nondeterminism ! Root cause of doom
  • 9. Brogrammer1 State muta)on example A brogrammer is [...] a slang term for a macho, male programmer. A brogrammer might self-describe as a sociable programmer. — Wikipedia 1 Frans Hals, Oil on canvas, 1630. Source: classicprogrammerpain;ngs
  • 10. What brogrammer does? • drinkBeer • talk
  • 11. Stateful implementa*on class Brogrammer { constructor() { this.beers = 0; } drinkBeer() { /* ... */ } talk() { /* ... */ } }
  • 12. Stateful – drinkBeer it('increment number of drunk beers', () => { expect(brogrammer.drinkBeer()).toEqual(1); expect(brogrammer.drinkBeer()).toEqual(2); }); // Inside Brogrammer class drinkBeer() { return this.beers += 1; // encapsulates 'beers' }
  • 13. Stateful – talk tests it('says "Beer me up!" before drinking', () => { expect(brogrammer.talk()).toEqual("Beer me up!"); }); it('says "Yummy" after 1st beer', () => { brogrammer.drinkBeer(); expect(brogrammer.talk()).toEqual("Yummy"); }); it('says "I a<M dRuNk" after 10th beer', () => { brogrammer.drinkBeer(); // 8 x brogrammer.drinkBeer(); brogrammer.drinkBeer(); expect(brogrammer.talk()).toEqual("I a<M dRuNk"); });
  • 14. Stateful – talk implementa+on // Inside Brogrammer class talk() { return ({ 0: 'Beer me up!', 1: 'Yummy', // ... 10: 'I a<M dRuNk', })[this.beers] || ''; }
  • 15. How to remove state? Single source of truth
  • 16. Naïve stateless – implementa+on class Brogrammer { constructor(store) { this.store = store; } // ... }
  • 17. Naïve stateless – drinkBeer tests it('increment number of drunk beers', () => { const store = { beers: 0 }; const brogrammer = new Brogrammer(store); brogrammer.drinkBeer(); expect(store.beers).toEqual(1); });
  • 18. Naïve stateless – drinkBeer implementa+on // Inside Brogrammer class drinkBeer() { return this.store.beers += 1; }
  • 19. Naïve stateless – talk tests it('says "I a<M dRuNk" after 10th beer', () => { const store = { beers: 10 }; const brogrammer = new Brogrammer(store); expect(brogrammer.talk()).toEqual("I a<M dRuNk"); });
  • 20. Naïve stateless – talk implementa+on // Inside Brogrammer class talk() { return ({ 0: 'Beer me up!', 1: 'Yummy', // ... 10: 'I a<M dRuNk', })[this.store.beers] || ''; }
  • 21. Solu%on review ! Removed state from the Brogrammer ! Easier tes2ng " Lost encapsula-on
  • 22. How to improve? The Redux way
  • 24. Three Principles of Redux3 ! Single source of truth ! State is read-only ! Changes are made with pure func)ons 3 Source: Redux
  • 25. Three Principles of Redux Single source of truth console.log(store.getState()); // { // brogrammer: { // beers: 0 // } // }
  • 26. Three Principles of Redux State is read-only store.dispatch({ type: 'INCREMENT_BEERS', });
  • 27. Three Principles of Redux Changes are made with pure func3ons function brogrammer(state = {}, action) { switch (action.type) { case 'SET_BEERS': return { ...state, beers: 5, }; // case ... } }
  • 28. Redux – incrementBeers ac%on it('returns action with type INCREMENT_BEERS', () => { const action = incrementBeers(); expect(action).toEqual({ type: 'INCREMENT_BEERS' }); });
  • 29. Redux – incrementBeers ac%on const incrementBeers = () => ({ type: 'INCREMENT_BEERS', });
  • 30. Redux – brogrammer reducer it('returns state with incremented beers', () => { const state = { beers: 0 }; const action = incrementBeers(); const nextState = brogrammer(state, action); expect(nextState).toEqual({ beers: 1 }); });
  • 31. Redux – brogrammer reducer implementa)on const brogrammer = (state = {}, action) => { switch (action.type) { case 'INCREMENT_BEERS': return { ...state, beers: state.beers + 1 }; default: return state } }
  • 32. Redux – drinkBeer tests it('increment number of drunk beers', () => { const store = createStore({ beers: 0 }); const brogrammer = new Brogrammer(store); brogrammer.drinkBeer(); expect(store.dispatch) .toHaveBeenCalledWith(incrementBeers()); });
  • 33. Redux – drinkBeer implementa+on // Inside Brogrammer class drinkBeer() { return this.store.dispatch(incrementBeers()); }
  • 34. Redux – talk tests it('says "I a<M dRuNk" after 10th beer', () => { const store = createStore({ beers: 10 }); const brogrammer = new Brogrammer(store); expect(brogrammer.talk()).toEqual("I a<M dRuNk"); });
  • 35. Redux – talk implementa+on // Inside Brogrammer class talk() { return ({ 0: 'Beer me up!', 1: 'Yummy', // ... 10: 'I a<M dRuNk', })[this.store.get('beers')] || ''; }
  • 36. Solu%on review ! Easy tes(ng ! Be,er separa(on ! Explicit state changes ! Full control over state
  • 37. A few thoughts on Redux
  • 39. Mutable vs immutable // Mutable const items = ['foo']; items.push('bar'); items.push('baz'); console.log(items); // ["foo", "bar", "baz"]
  • 40. Mutable vs immutable // Immutable via immutable-js const items = Immutable.List.of('foo'); items.push('bar'); items.push('baz'); console.log(items.toArray()); // ["foo"] console.log(items.push('bar').push('baz').toArray()); // ["foo", "bar", "baz"]
  • 41. What about performance?5 5 Source: React.js Conf 2015 - Immutable Data and React
  • 42. Performance benchmark Array push 1,000,000 items: var list = []; for (var i = 0; i < 1000000; i++) { list.push(i); } 83 ms
  • 43. Performance benchmark Mori immutable vector conj 1,000,000 items: var list = mori.vector(); for (var i = 0; i < 1000000; i++) { mori.conj(list, i); } 288 ms
  • 44. Should update problem const form = { /* ... */ }; function submit(form) { if (hasChanged(form)) { doSomethingExpensive(form); } }
  • 45. Should update problem versioning let currentFormVersion; function hasChanged(form) { const formVersion = md5(JSON.stringify(form)); return formVersion !== currentFormVersion; }
  • 46. Should update problem dirty bits function hasChanged(form) { for (var field in form) { if (field.meta.dirty === true) { return true; } } return false; }
  • 47. Should update problem observable pa+ern const form = { /* ... */ }; Object.observe(form, changes => { doSomethingExpensive(form); }); form.firstName = 'Maciej'; form.lastName = 'Komorowski'; form.profession = 'Brogrammer'; // Not true :)
  • 48. Should update problem immutable let currentForm = { /* ... */ }; function hasChanged(form) { return currentForm !== form; }
  • 49. Memoiza(on example function memoize(fn) { var cache = {}; return function (arg) { var hash = arg === Object(arg) ? JSON.stringify(arg) // Wat? : arg; return hash in cache ? cache[hash] : (cache[hash] = fn.call(this, arg)); } }
  • 50. Memoiza(on example function rawSum(list) { return list.reduce((a, b) => a + b) } const sum = memoize(rawSum); const array = [0, 1, ...1000000]; sum(array); // 89 ms rawSum(array); // 51 ms sum(array); // 42 ms
  • 51. Advantages of immutability ! No defensive copies ! Can be faster ! Be3er for concurrency (no deadlocks)
  • 54. Quiz What f does? f = 0 : 1 : zipWith (+) f (tail f)
  • 55. Answer Generates Fibonacci sequence > let fibs = 0 : 1 : zipWith (+) fibs (tail fibs) > take 11 fibs [0,1,1,2,3,5,8,13,21,34,55]