Skip to content

Instantly share code, notes, and snippets.

@MohdSaifulM
Created December 1, 2022 16:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MohdSaifulM/8f95c64cebdcc5861b9803869ecdbe25 to your computer and use it in GitHub Desktop.
Save MohdSaifulM/8f95c64cebdcc5861b9803869ecdbe25 to your computer and use it in GitHub Desktop.
Algorithms - Recursion
function someRecursive(arr, fn) {
// Return false if arr is empty
if (arr.length === 0) return false;
// if function returns true on first element in array
if (fn(arr[0])) return true;
// else slice array and re run function
return someRecursive(arr.slice(1), fn);
}
// SAMPLE INPUT / OUTPUT
// Return true if fn returns true to any element in array else return false
const isOdd = val => val % 2 !== 0;
// someRecursive([1,2,3,4], isOdd) // true
// someRecursive([4,6,8,9], isOdd) // true
// someRecursive([4,6,8], isOdd) // false
// someRecursive([4,6,8], val => val > 10); // false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment