To enhance the quality of my code and improve its readability, I have decided to implement a currying functions approach and create pure helper functions for repetitive code snippets. One issue I noticed was the frequent existence/type checks throughout my project in order to prevent potential errors like 'type of undefined'.
These checks typically look like:
if (param){
action...
}
As a solution, I am considering developing a global helper function that takes two parameters; the 'param' to be checked and the 'action function' to execute if the check passes. The function will resemble this structure:
function isExist(param, action){
if (param){
action();
}
}
However, this function may not be suited for all scenarios. How can I optimize it to work efficiently and universally across different cases? Moreover, I would appreciate insights on whether this approach is appropriate or if there is a superior method to achieve my objective here?
Example:
if (userInput){
saveToDB(userInput);
}
if (valueFromDB){
performSomeAction();
}
if (username && password){
validate(username, password)
}
I aim to replace these separate checks at various points in my code with a single helper function, as shown below:
isExist( userInput, saveToDB(userInput) );
isExist( valueFromDB, performSomeAction );
isExist( (username && password), validate(username, password) );
This transformation condenses nine lines of code into just three, which aligns with my desired outcome.