Joey
Joey

Reputation: 1676

How can you check if a function in jQuery is empty?

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

Answers (2)

Micah Henning
Micah Henning

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

adeneo
adeneo

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() === "";
}​

FIDDLE

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() === "";
}​

FIDDLE

Upvotes: 3

Related Questions