Skip to content

Instantly share code, notes, and snippets.

@broerjuang
Last active December 7, 2016 19:04
Show Gist options
  • Save broerjuang/b7b6c0880ad310b3d47e799140d2d1d7 to your computer and use it in GitHub Desktop.
Save broerjuang/b7b6c0880ad310b3d47e799140d2d1d7 to your computer and use it in GitHub Desktop.
Learning about recursion using Javascript
// this function takes an array and double each component inside it
const double = (nums) => {
if(nums.length === 0) {
return []
} else {
return [2 * nums[0]].concat(double(nums.slice(1, nums.length)))
}
}
console.log(double([1,2,3,4]), "should be [ 2, 4, 6, 8 ]")
// this function remove odd element inside the array
const removeOdd = (nums) => {
if(nums.length === 0) {
return []
} else {
if(nums[0] % 2 === 0) {
return [nums[0]].concat(removeOdd(nums.slice(1, nums.length)))
} else {
return removeOdd(nums.slice(1, nums.length))
}
}
}
console.log(removeOdd([1,2,3,4,5,6,7,7,8,9]), "should be [ 2, 4, 6, 8 ]")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment