I need to create an object based on some properties of another given object, in my example setRules
, add properties to object status
.
Considering that the cases to be handled will increase increase I would like to figure out how to enhance readability.
I would like to know:
- Could a
switch
statement increase readability (please scroll code below to see version 02 of the script)? - Any better way to write this from readability point of view?
// version 01
var status = {};
function setRules(cmd) {
if (cmd.type === 'category' && cmd.action === 'add') {
status = {
app: {
isEdit: false,
hasPriority: true
},
category: {
lock: false
}
};
} else if (cmd.type === 'category' && cmd.action === 'edit') {
status = {
app: {
isEdit: true,
hasPriority: true
},
category: {
lock: true
}
};
} else if (cmd.type === 'category' && cmd.action === 'delete') {
status = {
app: {
isEdit: true,
hasPriority: false
},
category: {
lock: false
}
};
} else if (cmd.type === 'category' && cmd.action === 'read') {
status = {
app: {
isEdit: false,
hasPriority: false
},
category: {
lock: false
}
};
} else if (cmd.type === 'users' && cmd.action === 'read') {
status = {
app: {
isEdit: false,
hasPriority: false
},
category: {
lock: false
}
};
} else if (cmd.type === 'users' && cmd.action === 'edit') {
status = {
app: {
isEdit: true,
hasPriority: true
},
category: {
lock: true
}
};
}
}
setRules({type: 'users', action:'edit'});
// version 02
var status = {};
function setRules(cmd) {
if(cmd.type === 'category'){
switch (action) {
case 'add':
status = {
app: {
isEdit: false,
hasPriority: true
},
category: {
lock: false
}
};
break;
case 'edit':
status = {
app: {
isEdit: true,
hasPriority: true
},
category: {
lock: true
}
};
break;
case 'delete':
status = {
app: {
isEdit: true,
hasPriority: false
},
category: {
lock: false
}
};
break;
case 'read':
status = {
app: {
isEdit: false,
hasPriority: false
},
category: {
lock: false
}
};
break;
}
} else if (cmd.type === 'users') {
switch(action){
case 'read':
status = {
app: {
isEdit: false,
hasPriority: false
},
category: {
lock: false
}
};
break;
case 'edit':
status = {
app: {
isEdit: true,
hasPriority: true
},
category: {
lock: true
}
};
break;
}
}
}
setRules({type: 'users', action:'edit'});
status
up front and then just setting the boolean values based on yourcmd.type
andaction
? I suspect you could make a much shorter and more readable code that way. – SuperBiasedMan 23 hours ago