Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assert that a function has been bound early

Tags:

javascript

Description

For the purpose of a unit test, I would like to check if a particular function has been bound.

Example

function foo() {}
var bar = foo.bind(context);

assertBound(bar); // --> true
assertBound(foo); // --> false

Question

Is there someway to check that bar has been bound that doesn't require mocking the bind function?

Notes

While How to get [[boundthis]] from function is asking about getting the [[boundthis]], I am wondering about just checking it has been bound.

like image 710
MitMaro Avatar asked Oct 15 '15 14:10

MitMaro


1 Answers

{Function}.name in ES6

In ES6 all functions are given a static name property.

function aFunction () {}
console.log(aFunction.name) // => 'aFunction'

Unnamed functions like arrow functions have an empty string for their name:

var aFunction = function () {}
console.log(aFunction.name) // => ''

Both named and unnamed functions when bound to a context using Function#bind have their name preceded with 'bound ':

// Named function
function aFunction () {}
var boundFunc = aFunction.bind(this)
console.log(boundFunc.name) // => 'bound aFunction'

// Unnamed function
var anotherFunc = function () {} // or `anotherFunc = () => 0`
var anotherBoundFunc = anotherFunc.bind(this)
console.log(anotherBoundFunc.name) // => 'bound '

We can use this to see if a function is bound:

function assertBound (fn) {
    return typeof fn == 'function' && fn.name.startsWith('bound ');
}

Note: checking that the word bound has a space after it is important so that we don't catch functions like function boundFunction () {}, for example.

______

Function#toString in ES5

A hacky way to know if a user-defined function is bound in ES5 is to cast it to a string using Function#toString and looking for the text '[native code]':

function assertBound (fn) {
    return typeof fn == 'function' && fn.toString().indexOf('[native code]') > -1;
}
like image 101
sdgluck Avatar answered Oct 04 '22 10:10

sdgluck