Version: v0.8.1 - Beta.  We welcome contributors & feedback.

Option Maps

There are some cases where you should take a Map as a function argument.

Optional Arguments

Maps make it easy ignore the order of optional arguments, and to add new arguments later.

// ✕ NO - Have to provide an empty 2nd argument
//   to provide the 3rd argument.
getPosts($userId, '', 100)

// ✓ YES - simpler & clearer
getPosts($userId, { numPosts: 100 })

Boolean Arguments

Adding a keyword gives more meaning to standalone booleans.

// ✕ NO - What does 'true' mean here?
getPosts($userId, true)

// ✓ YES - Much clearer
getPosts($userId, { includeDrafts: true })

Flag Shortcut

You can use a dashed word as a shortcut for a boolean key.

getPosts($userId, -includeDrafts)

// ... is the same as:

getPosts($userId, { includeDrafts: true })

Forcing Booleans

In the rare case that you need to pass in a boolean (e.g. calling a PHP library), you can assign it to a variable first and THT will allow it.

// ✕ Not allowed
getTacos(true)

// ✓ Allowed
$isSpicy = true
getTacos($isSpicy)

Using Option Maps 

An option map is just a regular map used as a function argument.

You can validate an option map with the check method, which fills the incoming map with default values.

As a benefit, this also lets you use dot . notation after it is checked, since the key is guaranteed to exist.

fun getPosts($userId, $options = {}) {

    $options.check({
        numPosts: 10
        sortBy: 'publishDate'
        includeDrafts: false
    })

    if $options.includeDrafts {
        ...
    }
}

An error will be triggered if the caller provides an invalid key, or the incoming type does not match the type of the default. (e.g. number, boolean, etc.)

// ✕ ERROR - Key not found
getPosts($userId, { sort: 'title' })
                    ^^^^

// ✕ ERROR - Needs a number
getPosts($userId, { numPosts: true })
                              ^^^^

Validating Enum Strings

If you assign a pipe-delimited list of strings, the method will only accept one of those values.

The first item in the list will be the default if the key doesn’t exist in the original map.

// 'publishDate' is the default
$options.check({
    sortBy: 'publishDate|title|author'
})