jeudi 13 janvier 2022

How to handle different logic in an if block with out duplicating code?

What is the best way to handle an if block that does something but the conditionals are different?

Lets say I have this function in JavaScript.

const updateText1 = function (id) {
    const selector = $(id);
    selector.on('change', function () {
        const text = selector.val();
        if(seen[text]) {
            // update some fields here
        } else {
            //more stuff here
        }
    })
}

But then I need to do the same thing inside the if statement but with a different or similar conditional

const updateText2 = function (id) {
    const selector = $(id);
    selector.on('change', function () {
        const text = selector.val();
        if(seen[text] || text.trim() === '') {
            // update some fields here
        } else {
            //more stuff here
        }
    })
}

then else functions are used like this

obj1 = {
  test: function() { updateText1(this.id) }
}

obj2 = {
  test: function() { updateText2(this.id) }
}

I know I could just combine the logic together but, since both objects that this function is attached to are handling slightly different things I'm trying to keep my code DRY and not repeat the if body multiple times. I've tried injecting the logic like this

obj2 = {
  // logic code here
  test: function() { updateText2(this.id, logic) }
}

But this results in the code not updating since the value is gotten via the Jquerry on change. Am I over thinking this, Should I just combine the logic, or is there a better way to organize and handle this?

Aucun commentaire:

Enregistrer un commentaire