what is the best way to write this function without repeting some values and only add the needed value initialText
createThread = () => {
if (this.props.first) {
publishLow = window.google.createPublish({
readId : this.props.readId
});
} else {
publishLow = window.google.createPublish({
readId : this.props.readId,
// The value needed in this condition
initialText : this.props.initialText
});
}
};
CodePudding user response:
Well, you can refactor this way, to avoid the repetition
createThread = () => {
const { readId, first, initialText } = this.props;
const payload = { readId };
if (!first) payload.initialText = initialText;
publishLow = window.google.createPublish(payload);
}
Also added object deconstruction to make code more readable.
CodePudding user response:
I agree with Andy but if you would want to make it smaller here is my idea:
createThread = () => {
const arg = {
readId : this.props.readId
};
if (!this.props.first) {
arg["initialText"] = this.props.initialText;
}
publishLow = window.google.createPublish(arg);
};
CodePudding user response:
createThread = () => {
const { readId, first, initialText } = this.props;
const payload = first ? { readId } : { readId , initialText };
publishLow = window.google.createPublish(payload);
}