3
\$\begingroup\$

This is what I've come up with to construct a name using a javascript object and immutable.js:

const getFullName = ({ user }) => {
    if (!user || !user.get('response')) {
        return '';
    }
    return `${user.getIn(['response', 'firstName']) || ''} ${user.getIn(['response', 'lastName']) ||
        ''}`;
};

As you can see, it looks pretty ugly. I'm wondering if there is a way to clean this code up. This function is called in loop to show all the names in the dataset. I can imagine that this solution may not be a very efficient in such case.

\$\endgroup\$

1 Answer 1

3
\$\begingroup\$

Rather than repeating user.getIn(['response' twice, you can extract the response once into a variable. Also, both .getIn and .get accept a default value if the property isn't found in the collection, which you can use instead of || ''. For example, .get('foo') || '' is (existing falsey values aside) equivalent to .get('foo', '').

In up-to-date environments or if the code is being transpiled, you can use optional chaining to more concisely get the nested response if it exists.

Since you want to return something if one condition is fulfilled, and something else otherwise, rather than using if, you can make things more concise by using the conditional operator:

const getFullName = ({ user }) => {
    const response = user?.get('response');
    return !response
        ? ''
        : `${response.get('firstName', '')} ${response.get('lastName', '')}`;
};

console.log(getFullName({}));
console.log(getFullName({ user: Immutable.fromJS({}) }));
console.log(getFullName({ user: Immutable.fromJS({ response: { firstName: 'foo' } }) }));
console.log(getFullName({ user: Immutable.fromJS({ response: { firstName: 'foo', lastName: 'bar' } }) }));
<script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/3.8.2/immutable.min.js"></script>

\$\endgroup\$

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.