DEV Community 👩‍💻👨‍💻

Discussion on: Why I prefer objects over switch statements

squgeim profile image
Shreya Dahal • Edited on

I tend to do this in JS as well, but it was more of a habit I carried from Python, which does not have and the common way to replicate that behavior is to use objects (dicts).

I would put the cases in a closure instead of the function itself to save some memory (granted it's a tiny bit).

const getEditorType = (() => {
    const itsCodeEditor = () => 'It is a code editor';
    const itsIDE = () => 'It is an IDE';

    const editors = {
        atom: itsCodeEditor,
        sublime: itsCodeEditor,
        vscode: itsCodeEditor,
        webstorm: itsIDE,
        pycharm: itsIDE,
        default: () => 'unknown'

    return type => (editors[type] || editors.default)();