Advertisement
Guest User

Untitled

a guest
Sep 18th, 2019
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.86 KB | None | 0 0
  1. // e.g. "write a simple function that logs out the factor of a given number"
  2. // input '4' should return '24' since 4 * 3 * 2 * 1 = 24
  3. // input '6' should return '720' etc...
  4.  
  5. // First, discuss and consider the basic utility of a `while` loop
  6. function factor(number) {
  7. let result = 1;
  8. let count = number;
  9. while (count > 1) {
  10. result *= count;
  11. count--;
  12. }
  13. return result;
  14. }
  15.  
  16. console.log('should be 24', factor(4));
  17. console.log('should be 720', factor(6));
  18.  
  19. // alternatively just ask for a countdown function
  20. function countdownLoop(value) {
  21. while (value > 0) {
  22. console.log(value--);
  23. }
  24. return value;
  25. }
  26.  
  27. console.log(countdownLoop(10));
  28.  
  29. // discuss some downsides to a loop...
  30. // - state that's being maintained / changed in that function
  31. // ... how can we reproduce the functionality of a while loop without creating all that state
  32.  
  33. // recursion countdown
  34. // - discuss terminal condition
  35. function countdownRecursively(value) {
  36. if (value > 0) {
  37. console.log(value);
  38. return countdownRecursively(value - 1);
  39. } else {
  40. return value;
  41. }
  42. }
  43.  
  44. const terminal = countdownRecursively(10);
  45. console.log(terminal);
  46.  
  47. // Now the recursive function for getting a factorial
  48. function factorial(number) {
  49. if (number <= 0) {
  50. return 1;
  51. } else {
  52. return (number * factorial(number - 1));
  53. }
  54. }
  55.  
  56. console.log(factorial(6));
  57.  
  58. // discussion points, value of using recursive functions is clean code that you get.
  59. // We're performing a stateless operation.
  60. // We're not changing the value of any variables along the way.
  61. // We're having no side effects outside of the functions, so nothing outside is being changed.
  62. // We're testing for the terminal condition first. And that allows us to
  63. // exit quickly and cleanly from our recursive function.
  64.  
  65. // downsides of recursion
  66. // - high memory usage of deep recursion
  67. // - code difficult to read for those unfamiliar with recursion
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement