lundi 18 novembre 2019

Refactor if and else statement in JavaScript?

I have a if else statement that I would like to refactor. I've seen some examples online but I haven't found one that could help me. I'm still learning.

condition 1

if(p.timestamp === p.lastTimeStamp)
then let postData = {
                    room: p.room,
                    patient: p.id,
                    timestamp: p.timestamp,
}

condition 2

if (p.timestamp ! == p.lastTimeStamp) 
then the postData will have one extra key that is replace : p.lastTimeStamp
let postData = {
                    room: p.room,
                    patient: p.id,
                    timestamp: p.timestamp,
                    replace : p.lastTimeStamp
}

My current function looks like below. I would appreciate if you could give me idea of how to refactor the below. Many thanks

postRecord(patient) {

        this.state.patients.map(p => {

            let postData = {};

            if ((p.id === patient.id) && (p.timestamp !== p.lastTimeStamp)) {

                postData = { 
                    room: p.room,
                    patient: p.id,
                    timestamp: p.timestamp,
                    replace: p.lastTimeStamp
                };
            }

            if ((p.id === patient.id) && (p.timestamp === p.lastTimeStamp)) {

                postData = { 
                    room: p.room,
                    patient: p.id,
                    timestamp: p.timestamp,

                };
            }

            axios({
                method: 'post',
                url: '/record',
                data: postData
            })
                .then(res => {
                    this.setState({recordSuccess: (res.status === 200) });
                })
                .catch(err => { throw new Error(err); });
        });
    }

Aucun commentaire:

Enregistrer un commentaire