From 9b14332f347ffe1fbb604aa01279a3555e5e7466 Mon Sep 17 00:00:00 2001 From: nediakhelifi Date: Sun, 28 Mar 2021 21:45:01 +0100 Subject: [PATCH] recursion --- src/getElementsByClassName.js | 29 ++++++++++++++++++++++++++--- src/nthFibonacci.js | 4 ++++ src/power.js | 5 ++++- src/sumArray.js | 13 ++++++++++--- 4 files changed, 44 insertions(+), 7 deletions(-) diff --git a/src/getElementsByClassName.js b/src/getElementsByClassName.js index ce169b0..052dbeb 100644 --- a/src/getElementsByClassName.js +++ b/src/getElementsByClassName.js @@ -6,6 +6,29 @@ // But instead we're going to implement it from scratch: -var getElementsByClassName = function(className) { - // Your code here -}; \ No newline at end of file + + var getElementsByClassName = function(className) { + var results = []; + var checkNodes = function(node) { + // If the element contains the class className + if (node.classList && node.classList.contains(className)) { + // Add it to our result + results.push(node); + } + + // If the element contains child nodes + if (node.childNodes) { + // Loop through each child node + for (var i = 0; i < node.childNodes.length; i++){ + checkNodes(node.childNodes[i]) + } + // _.each(element.childNodes, function(item) { + // // Recursively call findElementsContainingClass until we've looped through all child nodes + // findElementsContainingClass(item); + // }); + } + } + // Start our recursive function + checkNodes(document.body); + return results + } \ No newline at end of file diff --git a/src/nthFibonacci.js b/src/nthFibonacci.js index a66be73..c11b289 100644 --- a/src/nthFibonacci.js +++ b/src/nthFibonacci.js @@ -17,6 +17,10 @@ // etc... var nthFibonacci = function(n) { + if(n<2){ + return n + } + else return( nthFibonacci(n-1)+ nthFibonacci(n-2)) // Your code here }; diff --git a/src/power.js b/src/power.js index 4f48746..5f4a3c0 100644 --- a/src/power.js +++ b/src/power.js @@ -13,5 +13,8 @@ // power(10, 3) => 1000 var power = function(base, exponent) { - // Your code here + if (exponent===0) + return 1 + else + return base*power(base,exponent-1) }; \ No newline at end of file diff --git a/src/sumArray.js b/src/sumArray.js index e0d85e7..324deaf 100644 --- a/src/sumArray.js +++ b/src/sumArray.js @@ -16,6 +16,13 @@ // sumArray([1, 2, 3, 4, 5]) => 15 -var sumArray = function(arr) { - // Your code here -}; \ No newline at end of file +var sumArray = function(arr){ + var result =0 + if (arr.length == 0) + return 0; + else + return result=+ arr.shift() + sumArray(arr.slice()); + +} + +