I want to be able to tell if a function is noop. I was looking for a built in method such as angular.isNoop() but couldn't find anything. Is there anything that differentiates a noop?
I want to be able to tell if a function is noop. I was looking for a built in method such as angular.isNoop() but couldn't find anything. Is there anything that differentiates a noop?
A noop is simply a function that contains no operations. You can test for a specific noop function by using ===
For example;
console.log(x === angular.noop);
Will print true if x
was assign the noop from Angular, but this will not work if x
is using the noop from jQuery.
To check if a variable looks like a noop. You just need to see if the function string ends with {}
. You can try something like this.
console.log(angular.isFunction(x) && /\{\}$/.test(x.toString()));
The above should work even in the code is minified.
A noop function has a name just like any other function. That name is noop
. So you can check for it just by calling:
var theFunction = angular.noop;
theFunction.name === 'noop'
It is not a typical task, it is unlikely that the framework will have one.
function isNoop(fn) {
var trimRegex = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;
try {
return !fn.toString().match(/{([\s\S]*)}$/)[1].replace(trimRegex, '');
} catch (e) { };
}
It does not check for noop statements within function, of course. The credits for trimRegex
go to jQuery.