Using Array.prototype.findIndex()
- Store your conditions into Array
- Use Array.prototype.findIndex(). Just return the argument itself
(x) => x, it fill be treated as boolean and if true the method will return the index. Store the returned integer into a variable errIndex.
- If
errIndex is greater than -1 that means you have an "error" in the conditions array at that index
const conditions = [false, false, true, false, false];
const errIndex = conditions.findIndex(x => x);
if (errIndex > -1) {
console.log(`STOP IN CONDITION ${errIndex + 1}`);
} else {
console.log("All passed");
}
The nice thing about using .findIndex() is in that it can short-circuit the search and immediately return the index.
Not sure why, but given you want to return a String, and since return statements are used within a function, and since it's always preferable for a function to return the same type,
you could create a function that accepts an array of conditions and a success string as the second argument:
const status = (conditions, successMsg) => {
const idx = conditions.findIndex(x=>x);
return idx < 0 ? successMsg : `STOP IN CONDITION ${idx+1}`;
};
console.log(status([false, false, true, false, false], "OK")); // STOP IN CONDITION 3
console.log(status([false, false, false, false, false], "OK")); // OK
or you can create something similar based on the above idea, like a pass function in which you do not hardcode error strings, but instead it provides you with a callback function with argument being an Object with index property or null
const pass = (conditions, fn) => {
const index = conditions.findIndex(x => x);
fn(index < 0 ? null : {index});
};
pass([false, false, true, false, false], (err) => {
if (err) {
console.log(`STOP IN CONDITION ${err.index + 1}`)
return; // Exit function here
}
// All OK...
console.log("All OK! Do some work here");
});
if(!condition) { return ... }?ifconditional is not doing anything, you could even drop the curly braces (and the grouping operator as well):if(!conditionX) return "stop in conditionX";.