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'
 }
 }
 }
}
asked Jan 22, 2018 at 15:53
\$\endgroup\$

2 Answers 2

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([])
 }
 }
}
answered Feb 21, 2018 at 21:53
\$\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.

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

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.