-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
68 lines (54 loc) · 1.42 KB
/
Copy pathindex.ts
File metadata and controls
68 lines (54 loc) · 1.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import { parseNumber } from "../helper";
export type Method = (typeof Fibonacci.methods)[number];
export class Fibonacci {
sequence: number;
static methods = ["loop", "recursive"] as const;
/**
* @param {number} sequence
*/
constructor(sequence: number) {
this.sequence = parseNumber(sequence);
}
/**
* Create an array filled by fibonacci sequence using loop way.
*/
generateUsingLoop(): number[] {
let result = [];
let prev = 0;
let next = 1;
for (let index = 0; index < this.sequence; index++) {
result.push(prev);
const current = prev + next;
prev = next;
next = current;
}
return result;
}
/**
* Create an array filled by fibonacci sequence using recursive way.
*/
generateUsingRecursive(): number[] {
let result = [];
const get = (n: number): number =>
n < 1 ? 0 : n <= 2 ? 1 : get(n - 1) + get(n - 2);
for (let index = 0; index < this.sequence; index++) {
const current = get(index);
result.push(current);
}
return result;
}
/**
* Create an array filled by fibonacci sequence.
*/
generate(method: Method) {
if (method === "loop") {
return this.generateUsingLoop();
} else if (method === "recursive") {
return this.generateUsingRecursive();
} else {
throw new TypeError(
`Method must be one of this: ${Fibonacci.methods.join(",")}.`,
);
}
}
}