Advertisement
Guest User

Untitled

a guest
Nov 20th, 2017
53
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.57 KB | None | 0 0
  1. //main variable for storing solution.
  2. var ears;
  3.  
  4. /**
  5. * Sets collector variable to 0 and calls the recursion function.
  6. * @param {number} amountOfBunnies - The amount of bunnies that need to have ears counted.
  7. * @return {(number | string)} - Return either the solution or error message if parameters were invalid.
  8. */
  9. function recursiveCalculateEars(amountOfBunnies) {
  10. if (typeof amountOfBunnies == 'number'){
  11. ears = 0;
  12. return recursion(amountOfBunnies);
  13. } else {
  14. return 'Invalid parameters.';
  15. }
  16. /**
  17. * Main recursion function, recalls itself untill i == 0.
  18. * @param {number} i
  19. * @return {number} - The total amount of ears counted according to the variable ears.
  20. */
  21. function recursion(i){
  22. if (i > 0){
  23. ears += 2;
  24. return recursion(i - 1);
  25. } else if(i < 0){
  26. ears -= 2;
  27. return recursion(i + 1);
  28. } else if(i == 0){
  29. return ears;
  30. }
  31. }
  32. }
  33. /**
  34. * Iteratively calculates amount of bunny ears using a for loop.
  35. * @param {number} amountOfBunnies - The amount of bunnies to be calculated.
  36. * @return {(number | string)} - Return either the solution or error message if parameters were invalid.
  37. */
  38. function iterativeCalculateEars(amountOfBunnies){
  39. if (typeof amountOfBunnies == 'number'){
  40. ears = 0;
  41. if (amountOfBunnies > 0){
  42. for (var i = amountOfBunnies; i > 0; i--){
  43. ears += 2;
  44. }
  45. }else if (amountOfBunnies < 0){
  46. for (var i = amountOfBunnies; i < 0; i++){
  47. ears -= 2;
  48. }
  49. }
  50. return ears;
  51. } else {
  52. return 'Invalid parameters.'
  53. }
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement