Created
April 7, 2017 01:25
-
-
Save TiagoNunesDeveloper/7656c072e416764a2ee83662545bcd10 to your computer and use it in GitHub Desktop.
Recursão: Este conceito, também largamente utilizado na programação procedural, abre caminho para potencializar o uso de uma função. Com uma função que chama ela mesma em certas circunstâncias, criamos algoritmos capazes de percorrer estruturas aninhadas de arrays e objetos a fim de calcular valores, processar dados ou adaptar estas estruturas g…
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
//Regras --> Ela tem que chamar ela mesma. --> Tem que ter uma estratégia para parar a função. | |
const sum = (arr) => { | |
if(arr.length === 0){ | |
return 0 | |
} | |
return arr[0] + sum(arr.slice(1)) | |
} | |
//Usando ES6 | |
const sum = arr => { | |
if(arr.length === 0) | |
return 0 | |
const [head, ...tail] = arr | |
return head + sum(tail) | |
} | |
sum([1,2,3]) //=> 6 | |
const recursiveSum = collection => | |
collection.reduce((prev, curr) => | |
(Array.isArray(curr) | |
? prev + recursiveSum(curr) | |
: prev + curr), 0) | |
const collection = [1, [2, [3, 4]], 5] | |
recursiveSum(collection) //=> 15 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment