'if/else for specified function names that were called?
Is it possible to create an if else statement that depends on whether a certain function was called or not? If so, how do I define that in the if/else statement?
for example:
function getUseLocators(){
if (a function named 'function01' or 'function02' was called) {
return true;
} else {
return w.checkUseLocators.value;
}
}
Solution 1:[1]
There is no such thing as "function was called" in native JavaScript, you could do it with a higher order function like this:
function function01() {
console.log('function01');
}
function function02() {
console.log('function02');
}
const [makeObservableFunction, wasCalled] = (function() {
const called = [];
function make(func, name) {
return function(...args) {
called.push(name);
func(...args);
}
};
function wasCalled(name) {
return called.includes(name);
};
return [make, wasCalled];
})();
const observableFunction01 = makeObservableFunction(function01, 'function01');
const observableFunction02 = makeObservableFunction(function02, 'function02');
function getUseLocators() {
console.log(wasCalled('function01') || wasCalled('function02'));
}
getUseLocators();
observableFunction01();
getUseLocators();
Solution 2:[2]
You will need to store state to figure out if it was called.
let wasCalled = false;
function one(){
wasCalled = true;
}
function two(){
if (wasCalled) {
console.log('One was called');
} else {
console.log('One was not called');
}
}
two();
one();
two();
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | epascarello |
