Here's how to implement the Fibonacci sequence in TypeScript using recursion:
index.ts122 chars7 lines
However, this implementation is not very efficient as it computes the same sub-problems over and over again. To optimize it, we can use memoization.
Here's an implementation using memoization and an array:
index.ts217 chars11 lines
The memo
array stores the previously computed values, so we can reuse them instead of recomputing them.
To use this implementation, simply call the fibonacci
function with the desired index:
index.ts40 chars2 lines
This will output the sixth number in the Fibonacci sequence, which is 8.
gistlibby LogSnag