Ambrosius Topor

Notiz — 2018-02-28

Approaches on the switch construct

Tweaking the existing construct

The foundation: A simple switch construct:

switch ($value) {
    case 'a':
        break;
    case 'b':
        break;
}

Applying some minor style changes:

switch ($value) {
    case 'a': {
        break;
    }
    case 'b': {
        break;
    }
}

Not sure about this though—while it makes the indentation cleaner, it also adds some distraction.

Implementation of a function

The idea here is to get rid of the break construct.

Function

function which(value, cases) {
    if (typeof cases[value] === 'function') return cases[value]()
    if (typeof cases.default === 'function') return cases.default()
}

Usage

x = which('a', {
    a: () => 'yes',
    default: () => 'no'
})

The downside of this: There is an object being initialized holding every case.

Refactor

function which(value, cases) {
    const getFunction = (value) => {
        return (typeof cases[value] === 'function') ? cases[value] : undefined
    }
    const fn = getFunction(value) || getFunction('default')
    if (!fn) {
        throw new Error(`Could not resolve case for value "${value}"`)
    }
    return fn()
}

Comments

There are no comments yet.

Thanks for your contribution!
Your comment will be visible once it has been approved.

An error occured—please try again.

Add Comment