Skip to content

Instantly share code, notes, and snippets.

@DevGW
Created December 29, 2022 13:45
Show Gist options
  • Save DevGW/f1ba3953059cd6fd1d4dc29387bcf2a1 to your computer and use it in GitHub Desktop.
Save DevGW/f1ba3953059cd6fd1d4dc29387bcf2a1 to your computer and use it in GitHub Desktop.
Javascript :: Recursion
// definition: when a function calls itself (can replace iteration loops)
// An example of copying array within array (deep copy) without recursion:
function deeperCopy(anArr) {
let copyArray = [];
for (let i = 0; i < anArr.length; i++) {
let currElem = anArr[i];
if (Array.isArray(currElem)) {
let innerArray = [];
for (j = 0; j < currElem.length; j++) {
let innerElem = currElem[j];
innerArray.push(innerElem);
}
copyArray.push(innerArray);
}
else copyArray.push(currElem);
}
return copyArray;
}
// make sure to put a stop condition, commonly known as the 'base case'
function countdown(num) {
console.log(num);
countdown(num-1) while num >= 0; // <--- right here (or could use if statement)
}
// cache-ing
function cacheSavings(callback) {
let cache = {};
return function(anArg) {
if (!(anArg in cache)) {
let callbackResult = callback(anArg);
cache[anArg] = callbackResult;
}
return cache[anArg];
}
}
// counting to 10 using recursion
function countToTen(number) {
console.log(number);
(number < 10)? countToTen(number+1) : 10;
}
// cutting off string letter by letter from the end first:
function backwardString(myString) {
console.log(myString[myString.length-1]);
// We remove a piece of the original input as we recurse, until we get to nothing left.
if (myString.length > 1) backwardString(myString.slice(0, -1));
}
// using recursive to return a value; in this case a sum of all the numbers between aNum and 1
function sumNums(aNum) {
if (aNum === 1) return 1;
return aNum + sumNums(aNum - 1);
}
// count vowels in a string using recursion
function countVowels(aStr) {
const VOWELS = 'aeiouAEIOU';
// At the end we return 0 - so that nothing gets added to the total for the final empty string
if (!aStr.length) return 0;
// we grab the first character of each string and see if its a vowel
const firstChar = aStr[0];
// if it is, we add one, if it isnt, we just move onward
if (VOWELS.indexOf(firstChar) !== -1) {
return 1 + countVowels(aStr.slice(1));
} else {
return countVowels(aStr.slice(1));
}
}
// could have also used a helper method in the following solution:
function countVowels(string) {
// base case: if string.length === 0, it doesn't have any vowels
if (string.length === 0) {
return 0;
}
// recursive case: string.length must get closer to 0
let numVowels = 0;
// if the first letter is a vowel...
if (isAVowel(string[0])) {
// ...increment the numVowels
numVowels += 1;
}
// add the count of vowels in the remaining characters of the string
numVowels += countVowels(string.slice(1))
return numVowels;
}
// helper function that returns true if the character is a vowel
function isAVowel(char) {
let vowels = ['a', 'e', 'i', 'o', 'u'];
return vowels.includes(char);
}
// reverses an array. remember that concat is how to add arrays together
function reverseArray(anArr) {
if (anArr.length === 1) return anArr;
const lastElement = anArr[anArr.length-1];
return [lastElement].concat(reverseArray(anArr.slice(0,-1)));
}
// remember sumDigits is a function calling itself over again! That is recursion!!!
function sumDigits(aNum) { // 123
const stringNum = aNum.toString();
if (stringNum.length === 1) return parseInt(stringNum);
let restOfString = stringNum.slice(1);
let nextNumber = parseInt(restOfString);
return parseInt(stringNum[0]) + sumDigits(nextNumber);
}
// testing to see if it isnt a palindrome (really testing for falsification)
function isPalindrome(aStr) {
if (aStr.length <= 1) return true;
let firstChar = aStr[0].toLowerCase();
let lastChar = aStr[aStr.length -1].toLowerCase();
if (firstChar === lastChar) return isPalindrome(aStr.slice(1, -1)); // slice rtns aStr with first&last chars chopped off
else return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment