O slideshow foi denunciado.
Seu SlideShare está sendo baixado. ×

JS Experience 2017 - Javascript Funcional

Anúncio
Anúncio
Anúncio
Anúncio
Anúncio
Anúncio
Anúncio
Anúncio
Anúncio
Anúncio
Anúncio
Anúncio
Carregando em…3
×

Confira estes a seguir

1 de 100 Anúncio

Mais Conteúdo rRelacionado

Diapositivos para si (20)

Semelhante a JS Experience 2017 - Javascript Funcional (20)

Anúncio

Mais de iMasters (20)

Mais recentes (20)

Anúncio

JS Experience 2017 - Javascript Funcional

  1. 1. PROGRAMAÇÃO FUNCIONAL EM JAVASCRIPT
  2. 2. PROGRAMAÇÃO FUNCIONAL EM JAVASCRIPT COMO E POR QUÊ?
  3. 3. Sim, é minha única foto boa e eu uso ela pra tudo. Estudante de Ciência da Computação apaixonado por programação funcional e pesquisador independente (do grego: de mentira) em linguagens de programação. Não tenho muita coisa interessante pra falar de mim mesmo então vou preencher o slide com lorem ipsum dolor sit amet, consectetur adipiscing elit. ARTHUR XAVIER
  4. 4. — BRET VICTOR “A tecnologia muda rápido, mas o modo de pensar das pessoas muda devagar.”
  5. 5. THE FUTURE OF PROGRAMMING BRET VICTOR youtu.be/8pTEmbeENF4 “Pode haver muita resistência a novas formas de trabalho que demandem que você desaprenda o que já aprendeu e pense de forma diferente.”
  6. 6. s : → ℤ = α ↦ 0 se α = ε x + s(β) se α = x • β f : ℤ → ℕ = x ↦ |x|JEITO ESTILO PARADIGMAMINDSET
  7. 7. O QUE É PROGRAMAR?
  8. 8. TRANSFORMAR PROBLEMAPROBLEMAPROBLEMAPROBLEMAPROBLEMA
  9. 9. TRANSFORMAR SOLUÇÃO
  10. 10. PROBLEMAPROBLEMAPROBLEMAPROBLEMAPROBLEMA DECOMPOR
  11. 11. SOLUÇÃO DECOMPOR
  12. 12. MINDSET
  13. 13. λ?
  14. 14. PROGRAMAÇÃO IMPERATIVA PROGRAMAÇÃO DECLARATIVA VS.
  15. 15. // const values : Array<number>; console.log(values.map(x => x*x));
  16. 16. // const values : Array<number>; let squares = []; for (let value of values) { squares.push(value*value); } console.log(squares);
  17. 17. // const names : Array<string>; let promises = []; for (let name of names) { promises.push(name); } Promise.all(promises);
  18. 18. // const names : Array<string>; Promise.all(names.map(getUserByName));
  19. 19. // const userId : string; const steps = [ removeUserComments, removeUserPosts, removeUserFriends, removeUserData, ]; for (let step of steps) { await step(userId); }
  20. 20. // const userId : string; // Promise.sequence = ps => Promise.reduce(ps, (_, p) => p); const steps = [ removeUserComments, removeUserPosts, removeUserFriends, removeUserData, ]; return Promise.sequence(steps.map(f => f(userId)));
  21. 21. // const userIds : Array<string>; const steps = [ removeUserComments, removeUserPosts, removeUserFriends, removeUserData, ]; for (let userId of userIds) { for (let step of steps) { await step(userId); } }
  22. 22. // const userIds : Array<string>; const steps = [ removeUserComments, removeUserPosts, removeUserFriends, removeUserData, ]; return Promise.sequence(steps.map(step => userIds.map(step)));
  23. 23. // const userIds : Array<string>; const steps = [ removeUserComments, removeUserPosts, removeUserFriends, removeUserData, ]; const promises = steps.map(step => userIds.map(step)); return Promise.sequence(promises);
  24. 24. // const userIds : Array<string>; const steps = [ removeUserComments, removeUserPosts, removeUserFriends, removeUserData, ]; for (let step of steps) { await Promise.all(userIds.map(userId => step(userId)); }
  25. 25. // const userIds : Array<string>; const steps = [ removeUserComments, removeUserPosts, removeUserFriends, removeUserData, ]; const runStepOnUsers = step => Promise.all(userIds.map(step)); return Promise.sequence(steps.map(runStepOnUsers));
  26. 26. PROGRAMAÇÃO IMPERATIVA PROGRAMAÇÃO DECLARATIVA VS.
  27. 27. λ¿
  28. 28. — EU “Paradigma de programação onde computações são representadas por funções ou expressões puras, evitando efeitos colaterais e dados mutáveis, e que utiliza amplamente de composição de funções e funções de primeira classe.”
  29. 29. ≠FUNÇÃO PROCEDIMENTO
  30. 30. X Y x f(x) f : X → Y
  31. 31. FUNÇÃO (PURA)
  32. 32. — WIKIPEDIA “Uma função ou expressão produz efeitos colaterais se ela modifica algum estado fora de seu escopo ou realiza alguma interação observável com as funções que a chamaram ou com o mundo externo.”
  33. 33. function append(x) { this.array.push(x); }
  34. 34. function appendTo(array, x) { array.push(x); }
  35. 35. function appendTo(array, x) { return [...array, x]; }
  36. 36. IMUTABILIDADE
  37. 37. function increment(counter) { counter.value += 1; }
  38. 38. function increment(counter) { return { ...counter, value: counter.value + 1, }; }
  39. 39. function increment(counter) { counter = { ...counter, value: counter.value + 1, }; return counter; }
  40. 40. EFEITOS COLATERAIS
  41. 41. function sumOfSquares(array) { let result = 0; for (let x of array) { result += x*x; } console.log(result); };
  42. 42. function sumOfSquares(array) { let result = 0; for (let x of array) { result += x*x; } Database.deleteEverything(); console.log(result); };
  43. 43. function sumOfSquares(array) { let result = 0; for (let x of array) { result += x*x; } return result; }; console.log(sumOfSquares([2, 3, 5]));
  44. 44. const square = x => x*x; const add = (a, b) => a + b; function sumOfSquares(array) { return array.map(square).reduce(add, 0); } console.log(sumOfSquares([2, 3, 5]));
  45. 45. function sumOfSquares(array) { return array.reduce((x, sum) => sum + x*x, 0); } console.log(sumOfSquares([2, 3, 5]));
  46. 46. EFEITOS COLATERAIS?
  47. 47. EFEITOS!
  48. 48. DADOS EFEITOS EFEITOS EFEITOS EFEITOS
  49. 49. COMPOSIÇÃO
  50. 50. function* watchLoadMoreStarred() { while (true) { const {login} = yield take(actions.LOAD_MORE_STARRED); yield fork(loadStarred, login, true); } } function* loadStarred(login, loadMore) { const starredByUser = yield select(getStarredByUser, login); if (!starredByUser || loadMore) yield call(fetchStarred, login, starredByUser.nextPageUrl); }
  51. 51. function* watchLoadMoreStarred() { while (true) { const {login} = yield take(actions.LOAD_MORE_STARRED); yield fork(loadStarred, login, true); } } function* loadStarred(login, loadMore) { const starredByUser = yield select(getStarredByUser, login); if (!starredByUser || loadMore) yield call(fetchStarred, login, starredByUser.nextPageUrl); }
  52. 52. function* watchLoadMoreStarred() { while (true) { const {login} = yield take(actions.LOAD_MORE_STARRED); yield fork(loadStarred, login, true); } } function* loadStarred(login, loadMore) { const starredByUser = yield select(getStarredByUser, login); if (!starredByUser || loadMore) yield call(fetchStarred, login, starredByUser.nextPageUrl); }
  53. 53. function* watchLoadMoreStarred() { while (true) { const {login} = yield take(actions.LOAD_MORE_STARRED); yield fork(loadStarred, login, true); } } function* loadStarred(login, loadMore) { const starredByUser = yield select(getStarredByUser, login); if (!starredByUser || loadMore) yield call(fetchStarred, login, starredByUser.nextPageUrl); }
  54. 54. FUNÇÕES DE PRIMEIRA CLASSE
  55. 55. =FUNÇÃO VALOR
  56. 56. function* watchLoadMoreStarred() { while (true) { const {login} = yield take(actions.LOAD_MORE_STARRED); yield fork(loadStarred, login, true); } } function* loadStarred(login, loadMore) { const starredByUser = yield select(getStarredByUser, login); if (!starredByUser || loadMore) yield call(fetchStarred, login, starredByUser.nextPageUrl); }
  57. 57. FUNÇÕES DE ALTA ORDEMALTA
  58. 58. ABSTRAÇÃOABSTRAÇÃOABSTRAÇÃOABSTRAÇÃOABSTRAÇÃOABSTRAÇÃOABSTRAÇÃOABSTRAÇÃOABSTRAÇÃOABSTRAÇÃOABSTRAÇÃOABSTRAÇÃO
  59. 59. OTIMIZAÇÃO
  60. 60. ABSTRAÇÃOABSTRAÇÃOABSTRAÇÃOABSTRAÇÃOABSTRAÇÃOABSTRAÇÃOABSTRAÇÃOABSTRAÇÃOABSTRAÇÃOABSTRAÇÃOABSTRAÇÃOABSTRAÇÃO
  61. 61. mapfilter reduce
  62. 62. function buildElements(n, factory) { return Array(n).fill(0) .map(Math.random) .map(factory); } appendToDom(10, x => <h2>{x}</h2>);
  63. 63. function buildElements(n, factory) { return Array(n).fill(0) .map(Math.random) .map(factory); } appendToDom(10, h2);
  64. 64. function buildElements(n, factory) { return Array(n).fill(0) .map(compose(factory, Math.random)); } appendToDom(10, h2);
  65. 65. λ!
  66. 66. function getAvatarURL(user) { return Maybe(user) .then(user => user.avatar) .then(avatar => avatar.url); } getAvatarURL({ avatar: { url: 'barbaz' } }); // == Maybe('test') getAvatarURL(null); // == Maybe(null) getAvatarURL({ name: 'foobar' }); // == Maybe(null)
  67. 67. function getAvatarURL(user) { let user; return Maybe(user) .then(_user => { user = _user; return _user.name; }) .then(name => user.hasPage ? nameToURL(name) : null); } generateUserURL({ name: 'foobar', hasPage: true }); // == Maybe('https://fezbok/foobar') generateUserURL({ name: 'barbaz' }); // == Maybe(null) generateUserURL(null); // == Maybe(null) getAvatarURL({ hasPage: true }); // == Maybe(null)
  68. 68. function Do(m, f) { const gen = f(); function doRec(v) { const {value, done} = gen.next(v); const valueM = value instanceof m ? value : m.of(value); return done ? valueM : valueM.then(doRec); } return doRec(undefined); }
  69. 69. function generateUserURL(userMaybe) { return Do(Maybe, function*() { let user = yield userMaybe; let name = yield user.name; return user.hasPage ? nameToURL(name) : null; }); } generateUserURL({ name: 'foobar', hasPage: true }); // == Maybe('https://fezbok/foobar') generateUserURL({ name: 'barbaz' }); // == Maybe(null) generateUserURL(null); // == Maybe(null) getAvatarURL({ hasPage: true }); // == Maybe(null)
  70. 70. // Promise.of = Promise.resolve; Do(Promise, function*() { let hello = yield new Promise(resolve => { setTimeout(() => resolve('Hello'), 1000); }); let world = yield 'world!'; console.log(hello, world); });
  71. 71. // Array.of = a => [a]; // Array.prototype.then = function(f) { // return [].concat.apply([], this.map(f)); // }; Do(Array, function*() { let a = yield [1, 2, 3]; let b = yield ['a', 'b']; console.log(a, b); }); // 1, 'a' // 1, 'b' // 2, 'a' // 2, 'b' // 3, 'a' // 3, 'b'
  72. 72. // Array.of = a => [a]; // Array.prototype.then = function(f) { // return [].concat.apply([], this.map(f)); // }; Do(Array, function*() { let a = yield [1, 2, 3]; let b = yield ['a', 'b']; console.log(a, b); }); // 1, 'a' // 1, 'b' // 2, 'a' // 2, 'b' // 3, 'a' // 3, 'b'
  73. 73. // Array.of = a => [a]; // Array.prototype.then = function(f) { // return [].concat.apply([], this.map(f)); // }; [1, 2, 3].then(a => { ['a', 'b'].then(b => console.log(a, b)); }); // 1, 'a' // 1, 'b' // 2, 'a' // 2, 'b' // 3, 'a' // 3, 'b'
  74. 74. λ!
  75. 75. ?
  76. 76. 1Evite mutação Use dados e APIs imutáveis e sempre use const ao invés de let e var. Reduz o risco de estado compartilhado;
  77. 77. 2Evite dependências implícitas Podem trazer efeitos colaterais indesejados e estado compartilhado. this é uma dependência implícita;
  78. 78. 3Desacople dados e comportamento Pense em unidades de trabalho pequenas e genéricas. Abstraia e componha.
  79. 79. — EU “Programação funcional é uma ótima ferramenta para controle de complexidade.”
  80. 80. O(n²)
  81. 81. AbstractSingletonProxyFactoryBeanImpl
  82. 82. 1 Difícil de identificar e decompor em partes; 2 Depende de recursos compartilhados; 3 Ligado a uma ordem de execução predefinida. CÓDIGO IMPERATIVO É DIFÍCIL DE TESTAR Difícil de identificar e decompor em partes; Depende de recursos compartilhados; Ligado a uma ordem de execução predefinida.
  83. 83. 1 Difícil de identificar e decompor em partes; 2 Depende de recursos compartilhados; 3 Ligado a uma ordem de execução predefinida. CÓDIGO IMPERATIVO É DIFÍCIL DE REFATORAR Difícil de identificar e decompor em partes; Depende de recursos compartilhados; Ligado a uma ordem de execução predefinida.
  84. 84. 1 Difícil de identificar e decompor em partes; 2 Depende de recursos compartilhados; 3 Ligado a uma ordem de execução predefinida. CÓDIGO IMPERATIVO É DIFÍCIL DE ENTENDER Difícil de identificar e decompor em partes; Depende de recursos compartilhados; Ligado a uma ordem de execução predefinida.
  85. 85. CÓDIGO FUNCIONAL É FÁCIL DE ENTENDER 1 Difícil de identificar e decompor em partes; 2 Depende de recursos compartilhados;asdasda sdas 3 Ligado a uma ordem de execução predefinida. Força a decomposição de tarefas complexas; Abstrai e generaliza estruturas de controle de fluxo; Completamente previsível.
  86. 86. REQUER DESAPRENDER
  87. 87. REQUER REAPRENDER
  88. 88. Brian Lonsdorf (Dr. Boolean) PROFESSOR FRISBY’S MOSTLY ADEQUATE GUIDE TO FUNCTIONAL PROGRAMMING
  89. 89. Luis Atencio FUNCTIONAL PROGRAMMING IN JAVASCRIPT
  90. 90. Evan Czaplicki ELM
  91. 91. @arthurxavierx @arthur-xavier goo.gl/kL4SNH

×