Advertisement
elena1234

Closure (JavaScript) with Fibonacci

Nov 23rd, 2021
1,341
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function getFibonator() {
  2.     let prevNum = 0;
  3.     let currentNum = 1;
  4.  
  5.     return function() {
  6.         let nextNum = prevNum + currentNum;
  7.         prevNum = currentNum;
  8.         currentNum = nextNum;
  9.         return prevNum;
  10.     }
  11. }
  12.  
  13.  
  14. let fib = getFibonator();
  15. console.log(fib()); // 1
  16. console.log(fib()); // 1
  17. console.log(fib()); // 2
  18. console.log(fib()); // 3
  19. console.log(fib()); // 5
  20. console.log(fib()); // 8
  21. console.log(fib()); // 13
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement