Examples usages of recursion
14 August 2022 (Updated 12 March 2023)
Example 1: Recursively count the number of elements in an array
This is a solution to this kata.
function deepCount(arr) {
let count = 0
// Loop through each item
for (let item of arr) {
// If element is an array, call deepCount again
if (Array.isArray(item)) {
count += deepCount(item)
}
// Otherwise, increment count
count += 1
}
return count
}
// deepCount([]) => 0
// deepCount([1, 2, 3]) => 3
// deepCount(["x", "y", ["z"]]) => 4
// deepCount([1, 2, [3, 4, [5]]]) => 7
Example 2: Manipulate function argument until some condition is true
This is a solution to this kata:
So, your task is to sum up all the digits in string, possibly multiple times, till you get a one digit result. You should then return it as a string. The input will be always valid.
const str = '1234'
digitSum(str) // returns 1
/* 1 + 2 + 3 + 4 = 10 => this result doesn't have one digit => 1 + 0 = 1 */
function digitSum(numStr) {
// Get digits sum (e.g., 10)
const digitsSum = numStr.split('').reduce((sum, num) => sum + Number(num), 0).toString()
// If sum.length === 1, return sum
if (digitsSum.length === 1) {
return digitsSum
}
// Else, call function again
return digitSum(digitsSum)
}
Example 3
Solution to this kata. I need to elaborate on how this works.
function getElement(array, indices) {
if (indices.length === 1) {
return array[indices]
}
return getElement(array[indices[0]], indices. Slice(1))
}
Example 4
Solution to this kata:
function removeParentheses(str) {
const result = str.replace(/\([A-Za-z0-9\s]*\)/g, '')
if (result.includes('(') && result.includes(')')) {
return removeParentheses(result)
}
return result
}
Tagged:
Snippets
Thanks for your comment 🙏. Once it's approved, it will appear here.
Leave a comment