r/javascript • • Oct 09 '18

Writing Lighter, Faster JavaScript Functions

https://medium.com/p/c631739af349
40 Upvotes

23 comments sorted by

View all comments

2

u/nullified- Oct 09 '18

Performance issues aside, when would one be inclined to write a function like this "unoptimized" one?

An array literal inside a function that checks if the array contains an item is beyond contrived. Hence, I'm having trouble generalizing this pattern to something not contrived.

1

u/hypernautical Oct 10 '18 edited Oct 10 '18

I tend to write lots of functions that reference a constant object in two situations currently. One is to check an argument against a list of types that have one response vs. a more common one. This avoids long IF clause with lots of ORs:

function getUserDisplayName (userObject) {
    const userTypesWithTitles = [1, 2, 3, 5]
    if (userTypesWithTitles.includes(userObject.type)) {
        return `${userObject.title} ${userObject.name}`
    } else {
        return `${userObject.name}`
    }
}

The second use is also avoiding lots if IF...ELSE IF.. clauses using a "map":

function getUserLongTitle (userObject) {
    const userLongTitleMap = {
        'ceo': 'Chief Executive Officer',
        'cfo': 'Chief Financial Officer',
        'coo': 'Chief Operations Officer
    }
    return userLongTitleMap[userObject.shortTitle]
}

I use these all the time, mostly the latter, when I know there are particular front-end display requirements beyond the virgin data sent to me by the server. The former could also be used for permission or different content display booleans, etc.