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
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 ...
}
}
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 :)
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