Match

8/15/2020

A small helper function that aims to simulate the match expression in PHP.

const match = (input, patterns) => {
    return patterns[input] || patterns['default']
}

Instead of doing this:

const getStatusCode = code => {
    const lookup = {
        200: 'Success',
        300: 'Redirect',
        400: 'Client error',
        // ...
    }

    return lookup[code]
}

const status = getStatusCode(200) // Success

You can do this:

const getStatusCode = code =>
    match(code, {
        200: 'Success',
        300: 'Redirect',
        400: 'Client error',
        // ...
    })

const status = getStatusCode(200) // Success