Reputation: 1676
How would you check if the function that does exist and is defined, is empty or not? For example:
function foo(){
// empty
}
function bar(){
alert('something');
// not empty
}
Is there a function or a a simple way to check this?
Upvotes: 0
Views: 757
Reputation: 2185
A function could be empty but still be passed variables. This would error in adeneo's function:
function bar(t) { }
Modifying the regex, here is the same function with support for variables:
function isEmpty(f) {
return typeof f === "function" && /^function [^(]*\([^)]\)[ ]*{(.*)}$/.exec(
f.toString().replace(/\n/g, "").replace(/(\/\*[\w\'\s\r\n\*]*\*\/)|(\/\/[\w\s\']*)|(\<![\-\-\s\w\>\/]*\>)/g, '')
)[1].trim() === "";
}
Upvotes: 1
Reputation: 318302
It's not really very useful, and generally not a good idea, but you could do:
function foo(){
}
function bar(){
alert('something');
// not empty
}
console.log('foo is empty :' + isEmpty(foo));
console.log('bar is empty :' + isEmpty(bar));
function isEmpty(f) {
return typeof f === "function" && /^function [^(]*\(\)[ ]*{(.*)}$/.exec(
f.toString().replace(/\n/g, "")
)[1].trim() === "";
}
If it's just to check a callback, the normal way would be just to check if the callback is a function:
if (typeof callback === 'function') callback.call();
EDIT:
To also disregard comments :
function isEmpty(f) {
return typeof f === "function" && /^function [^(]*\(\)[ ]*{(.*)}$/.exec(
f.toString().replace(/\n/g, "").replace(/(\/\*[\w\'\s\r\n\*]*\*\/)|(\/\/[\w\s\']*)|(\<![\-\-\s\w\>\/]*\>)/g, '')
)[1].trim() === "";
}
Upvotes: 3