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

Option Maps

Basics 

THT encourages the use of Maps for arguments in a couple of cases:

  1. Boolean arguments, because they make the code easier to understand.
  2. Optional arguments, because it is easier to add new options later.

For example:

// ✕ What do these arguments mean?
getPosts($userId, 100, '', true)

// ✓ Much clearer
getPosts($userId, { numPosts: 100, includeDrafts })

How to Create an Option Map 

An option map is just a regular map.

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

    if $options['includeDrafts'] {
        ...
    }
}

Validating Option Maps 

You can validate an option map with the check method, which takes a Map of default values.

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

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

An error will be triggered if the incoming type does not match the type of the default. (e.g. number, boolean, etc.)

getPosts($userId, { SortBy: 'title' })
//                  ^^^^^^
// ✕ ERROR - Key case does not match

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

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

$options.check({
    includeDrafts: false,
})

if $options.includeDrafts {
    ...
}

Validating 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 no value is given.

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

Flag Shortcut 

If you have a single boolean, you can replace it with the -flag shortcut.

You will find this in many of THT's built-in methods.

$list.sort(-reverse)

// ... same as ...

$list.sort({ reverse: true })

Forcing Boolean Arguments 

THT doesn’t allow boolean literals as arguments because they don’t convey any real meaning on their own. (Booleans are still important INSIDE of functions.)

However, in the rare case that you need to pass in a boolean, you can assign it to a variable first, and THT will allow it.

// ✕ Not allowed
getTacos(true)

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