0
\$\begingroup\$

In the following code I want to return all the same keys and values except the property color. If the name is default, return the color: '#1F2532', if it's different than default, it will call a function that gives me random colors color: pickColor([]). But I think there is a better way to write this instead of repeating code and just changing the property color. How can I do this?

class Project {

  static createProject(data) {
    if (data.name !== 'default') {
      return {
        owner: {
          name: data.owner,
          avatar: data.ownerAvatar
        },
        users: [
          {
            name: data.owner,
            avatar: data.ownerAvatar,
            active: true,
          }],
        name: data.name,
        retrospectives: [],
        color: pickColor([])
      }
    } else {
      return {
        owner: {
          name: data.owner,
          avatar: data.ownerAvatar
        },
        users: [
          {
            name: data.owner,
            avatar: data.ownerAvatar,
            active: true,
          }],
        name: data.name,
        retrospectives: [],
        color: '#1F2532'
      }
    }
  }
}
\$\endgroup\$
2
\$\begingroup\$

As said in a comment above, using a conditional assignment would be your best bet:

class Project {

  static createProject(data) {
    return {
      owner: {
        name: data.owner,
        avatar: data.ownerAvatar
      },
      users: [
        {
          name: data.owner,
          avatar: data.ownerAvatar,
          active: true,
        }],
      name: data.name,
      retrospectives: [],
      color: data.name === 'default' ? '#1F2532' : pickColor([])
    }
  }
}
\$\endgroup\$
0
\$\begingroup\$

I am not familiar with javascript, so please excuse me if I get some semantics wrong. The simple answer is to change the position of "if".

class Project {
  static createProject(data) {
      return {
        owner: {
          name: data.owner,
          avatar: data.ownerAvatar
        },
        users: [
          {
            name: data.owner,
            avatar: data.ownerAvatar,
            active: true,
          }],
        name: data.name,
        retrospectives: [],
        if (data.name !== 'default') {
            color: pickColor([])
        } else {
        color: '#1F2532'
      }
    }
  }
}

An alternative to

    if (data.name !== 'default') {
        color: pickColor([])
    } else {
    color: '#1F2532'
  }

is

colour: (data.name == 'default' ? '#1F2532' : pickColor([]))

p.s. haven't counted the brackets either, but you get the drift.

\$\endgroup\$
  • 1
    \$\begingroup\$ You can't put an if-statement into an object literal. A conditional expression however should work fine. \$\endgroup\$ – le_m Jan 22 '18 at 20:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.