Skip to content

Commit 787fd75

Browse files
authored
Added FibonacciGenerator
This wasn't originally part of the PR, but I thought it would be good to add
1 parent c5fe0b5 commit 787fd75

File tree

1 file changed

+14
-3
lines changed

1 file changed

+14
-3
lines changed

Maths/Fibonacci.js

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
const list = []
21
// https://en.wikipedia.org/wiki/Generalizations_of_Fibonacci_numbers#Extension_to_negative_integers
32
const FibonacciIterative = (nth) => {
43
const sign = nth < 0
@@ -20,7 +19,20 @@ const FibonacciIterative = (nth) => {
2019
return sequence
2120
}
2221

22+
const FibonacciGenerator = function* (sign) {
23+
let a = 0
24+
let b = 1
25+
yield a
26+
while (true) {
27+
yield b
28+
[a, b] = sign ? [b, a - b] : [b, a + b]
29+
}
30+
}
31+
32+
const list = []
2333
const FibonacciRecursive = (number) => {
34+
const sgn = number < 0
35+
if (sgn) number *= -1
2436
return (() => {
2537
switch (list.length) {
2638
case 0:
@@ -32,7 +44,6 @@ const FibonacciRecursive = (number) => {
3244
case number + 1:
3345
return list
3446
default:
35-
const sgn = number < 0
3647
list.push(
3748
sgn ?
3849
list.at(-2) - list.at(-1)
@@ -45,7 +56,6 @@ const FibonacciRecursive = (number) => {
4556
}
4657

4758
const dict = new Map()
48-
4959
const FibonacciRecursiveDP = (stairs) => {
5060
const sgn = stairs < 0
5161
if (sgn) stairs *= -1
@@ -193,6 +203,7 @@ const FibonacciMatrixExpo = (n) => {
193203

194204
export { FibonacciDpWithoutRecursion }
195205
export { FibonacciIterative }
206+
export { FibonacciGenerator }
196207
export { FibonacciRecursive }
197208
export { FibonacciRecursiveDP }
198209
export { FibonacciMatrixExpo }

0 commit comments

Comments
 (0)