Examples usages of recursion
14 August 2022 (Updated 29 December 2022)
Example 1: Manipulate function argument until some condition is true
The following is a solution to this kata which describes the challenge as:
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 2
Solution to kata. 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 3
Solution to 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:
Algorithms / snippets