Chapter 4, Behaving Properly – Pure Functions
4.1 Must return? If a pure function doesn’t return anything, it means that the function doesn’t do anything since it can’t modify its inputs and doesn’t have any other side effect.
4.2 Well-specified return: TypeScript would have objected because the result of the function would be string | undefined, because the .pop() method returns undefined if the input array is empty.
4.3 Go for a closure: We just have to wrap the definition of fib2() in an IIFE; fibC() is equivalent to fib2() but with an internal cache:
// question_04_go_for_a_closure.ts
const fibC = (() => {
const cache: number[] = [];
const fib2 = (n: number): number => {
if (cache[n] === undefined) {
if (n === 0) {
cache[0] = 0;
} else if (n === 1) {
...