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 jQuery on change.
Am I overthinking this, should I just combine the logic, or is there a better way to organize and handle this?
Solution 1:
The simplest solution is to pass a callback, and that's probably what you were trying to do.
Example:
const updateText = function (id, predicate) {
const selector = $(id);
selector.on('change', function () {
const text = selector.val();
if(predicate(text)) {
// update some fields here
} else {
//more stuff here
}
})
}
which then could be called in the following way
function canUpdate1(text) {
return seen[text];
}
function canUpdate2(text) {
return seen[text] || text.trim() === '';
}
updateText('id1', canUpdate1);
updateText('id2', canUpdate2);