Integers in Range Recursion
Published in
Oct 1, 2020
Q. Write an algorithm that is the integers in range function with recursion.
const intInRangeRecursive = function (startValue, endValue) { if (endValue - startValue === 2) { return [startValue + 1]; } else { let list = intInRangeRecursive(startValue, endValue - 1); list.push(endValue - 1); return list; }}console.log(intInRangeRecursive(1, 5)); // [2, 3, 4]
- If
endValue — startValue === 2
, return[startValue + 1]
. - Otherwise, declare the
list
is equal to the functionintInRangeRecursive(startValue, endValue1)
. - Push the element
endValue — 1
tolist
. - Return
list
.
? 5 - 1 === 2 // False
list = intInRangeRecursive(1, 4)
list.push(4)
list = [4]? 4 - 1 === 2 // False
list = intInRangeRecursive(1, 3)
list.push(3)
list = [3, 4]? 3 - 1 === 2 // True // [1 + 1]
list = [2, 3, 4]