E aí pessoal! Belezura?
Hoje vamos falar sobre Arrow Functions, e como elas podem nos ajudar na produtividade quando trabalhamos com Node.js. Bora!
Tempos atrás, escrevi um post falando sobre expressões lambda e arrow functions, esse aqui. Lá, descrevi sobre um pacote chamado devbox-linq que foi inspirado no C# e tem várias funcionalidades que facilitam MUITO o desenvolvimento no nosso dia-a-dia. Volto novamente para falar desse pacote que passou por algumas mudanças e refatorações pra facilitar ainda mais!
Deixo aqui meus parabéns e agradecimentos ao Gustavo e o Lenon que passaram um bom tempo para refatorar e deixar esse pacote cada dia melhor 😀
O que são Arrow Functions mesmo?
As Arrow Functions vieram com o EcmaScript 6. E são basicamente uma “nova” forma de se trabalhar com funções utilizando o operador =>. Pra ser bem sucinto e ir direto ao assunto, vejam um exemplo de uma função do jeito “antigo”:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var soma = function (a, b) { | |
return a + b; | |
} |
E agora trabalhando com arrow functions:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var soma = (a, b) => { | |
return a + b; | |
} |
Ainda podemos simplificar mais ainda assim:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var soma = (a, b) => a + b; |
Certo, agora todo mundo sabe o que são arrow functions, né? Então vamos para o próximo passo!
Como as arrow functions podem ajudar na produtividade?
Quando comecei a fazer projetos com Node.js, estava muito acostumado com os projetos em C#, e confesso que senti muita falta de uma biblioteca chamada System.Linq, pois com ela conseguimos filtrar e manipular listas. Um exemplo básico, é somar todos os elementos de um array. Com C# fica mais ou menos assim:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var lstInt = new List<int> {1, 2, 3, 4, 5}; | |
var soma = lstInt.Sum(); |
Outro exemplo legal para falarmos do C#, é filtrar uma lista de clientes, onde queremos apenas clientes do sexo masculino com mais de 20 anos, que ficaria mais ou menos assim:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public IEnumerable<Cliente> ClientesMasculinosComMaisDeVinteAnos(IEnumerable<Cliente> clientes) | |
{ | |
//Reparem no uso da expressão Lambda | |
return clientes.Where(c => c.Idade > 20 && c.Sexo == "Masculino"); | |
} |
Pra fazer com JavaScript da maneira convencional, precisaríamos fazer de algumas maneiras… Primeiro vamos ver a forma mais convencional possível:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var lstInt = [1, 2, 3, 4, 5]; | |
var soma = 0; | |
for(var i = 0; i < lstInt.length; i++) { | |
soma = soma + lstInt[i]; | |
} | |
console.log(soma); //15 |
Existe uma maneira bem melhor, utilizando o “reduce“, que fica mais ou menos assim:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var lstInt = [1, 2, 3, 4, 5]; | |
var soma = lstInt.reduce(function(total, proximo) { | |
return total + proximo; | |
}); | |
console.log(soma); //15 |
Agora vamos adicionar as arrow functions junto ao reduce:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var lstInt = [1, 2, 3, 4, 5]; | |
var somar = (a, b) => a + b; | |
var soma = lstInt.reduce(somar); | |
console.log(soma); //15 |
Notem, que em cada uma das abordagens escrevemos cada vez menos código. Porém, com o uso do devbox-linq o negócio fica lindo! Vejam como fica o exemplo da soma:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var lstInt = [1, 2, 3, 4, 5]; | |
var soma = lstInt.sum(); //15 |
Não precisamos escrever quase NADA 🙂
Vejam um outro exemplo onde somamos elementos de um objeto:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var produtos = [ | |
{ nome: 'Café', preco: 10 }, | |
{ nome: 'Açucar', preco: 5 } | |
]; | |
var somaPreco = produtos.sum(x => x.preco); //15 |
Agora vejam o exemplo de filtro de clientes:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var clientes = [ | |
{ nome: 'Zé', sexo: 'Masculino', idade: 25 }, | |
{ nome: 'Tonho', sexo: 'Masculino', idade: 18 }, | |
{ nome: 'Maria', sexo: 'Feminino', idade: 25 } | |
]; | |
var clientesMasculinosMaioresDe20Anos = clientes.where(x => x.sexo == 'Masculino' && idade > 20); | |
// [ { nome: 'Zé', sexo: 'Masculino', idade: 25 } ] |
O que mais podemos fazer?
Temos várias possibilidades, vejam no exemplo abaixo um pouco do que podemos fazer:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require('devbox-linq'); | |
var listaDeCoisas = [ | |
{ id: 1, nome: 'Coisa 01', tipo: 'A' }, | |
{ id: 2, nome: 'Coisa 02', tipo: 'A' }, | |
{ id: 3, nome: 'Coisa 03', tipo: 'B' }, | |
{ id: 4, nome: 'Coisa 04', tipo: 'B' }, | |
{ id: 4, nome: 'Coisa 04', tipo: 'B' }, | |
{ id: 5, nome: 'Coisa 05', tipo: 'C' } | |
]; | |
var somenteTipoC = listaDeCoisas.where(x => x.tipo == 'C'); | |
// [ { id: 5, nome: 'Coisa 05', tipo: 'C' } ] | |
var primeiroTipoA = listaDeCoisas.first(x => x.tipo == 'A'); | |
// { id: 1, nome: 'Coisa 01', tipo: 'A' } | |
var existeAlgumTipoB = listaDeCoisas.any(x => x.tipo == 'B'); | |
// true | |
var quantidadeCoisasTipoA = listaDeCoisas.count(x => x.tipo == 'A'); | |
// 2 | |
var coisasSemRepetir = listaDeCoisas.distinct(); | |
/* | |
{ id: 1, nome: 'Coisa 01', tipo: 'A' }, | |
{ id: 2, nome: 'Coisa 02', tipo: 'A' }, | |
{ id: 3, nome: 'Coisa 03', tipo: 'B' }, | |
{ id: 4, nome: 'Coisa 04', tipo: 'B' }, | |
{ id: 5, nome: 'Coisa 05', tipo: 'C' } | |
*/ | |
var coisasAgrupadas = listaDeCoisas.groupBy(x => x.tipo); | |
/* | |
[ | |
[ | |
{ id: 1, nome: 'Coisa 01', tipo: 'A' }, | |
{ id: 2, nome: 'Coisa 02', tipo: 'A' } | |
], | |
[ | |
{ id: 3, nome: 'Coisa 03', tipo: 'B' }, | |
{ id: 4, nome: 'Coisa 04', tipo: 'B' }, | |
{ id: 4, nome: 'Coisa 04', tipo: 'B' } | |
], | |
[ | |
{ id: 5, nome: 'Coisa 05', tipo: 'C' } | |
] | |
] | |
*/ | |
console.log(coisasAgrupadas[0].key) // 'A' | |
var minimo = listaDeCoisas.min(x => x.id) | |
// 1 |
Além disso tem várias outras funcionalidades, como “orderBy“, “select“, “skip“, “take“, dentre tantas outras.
Como eu uso?
Para utilizar é só instalar o pacote via npm dessa maneira:
npm install devbox-linq
A documentação está bem legal, e você pode encontrar ela aqui: https://www.npmjs.com/package/devbox-linq
Caso não tenha alguma funcionalidade que você precisa, é só fazer um fork e mandar um pull request que estamos de braços abertos 🙂
O link do Github é esse aqui: https://github.com/GustavoMaritan/LinqJs
Por hoje é só, qualquer dúvida ou sugestão, estou à disposição! Até mais 😀
Muito bom parabens
GostarGostar
Topper demais, mão na roda
GostarGostar