Function totality

ยท

1 min read

A function is considered total when it is defined for all possible inputs.

Below is an example of a function that fails to meet this requirement.

type One = 1
type Two = 2
type Three = 3
type SumType = One | Two | Three

function fn(num: SumType): string {
    switch (num) {
        case 1: return '1'
        case 2: return '2'
        default:
            throw new Error('uh-oh, unexpected input (TโŒ“T)')
    }
}

This function is not total because it throws an exception when given the input value 3 or any other value.

Thus, this function is partial.

To make it total, we must implement handling for the missing cases. Alternatively, we can utilize built-in JavaScript APIs.

function fn(num: SumType): string {
    return num.toString()
}

Striving to write total functions is a crucial step toward creating more resilient and bug-free software all of us can make.

You might be thinking, "But Aman, in my job project, our functions take complex objects as inputs. How can I ensure they're all total?"

Stay with me as we explore more principles and patterns of functional programming to provide you with solutions!

ย