Function looking for a node that satisfies a callback

Asked

Viewed 36 times

2

I found an implementation of lists linked in javascript and saw this method that returns the first node that satisfies the callback condition and did not understand very well the first if, I understood that it checks if callback is a function "Object.prototype.toString.call(callback)", does this call a toString method using which callback is associated ? If I’m not mistaken.

Link if necessary to understand the context: Implementing a Linked List in Javascript

find(callback){
        if(Object.prototype.toString.call(callback) !== '[object Function]'){
            return new TypeError(callback + ' is not a function');
        };

        if(!this.head) return false;

        let currentNode = this.head;

        while(currentNode){
            if(callback && callback(currentNode.value)) {
                return currentNode;
            }
            currentNode = currentNode.next;
        };

        return undefined;
}

1 answer

1


That first if, like you said, it’s a backup to only run the rest of the code if callback is a function.

Use Object.prototype.toString.call(algo) it’s common to find out the kind of thing we went through to that .call(. This is one way to correct a language gap that is to have no native methods for all Types. However this method is itself not 100% reliable as the method .toString can be overwritten and return values that break this code. The possible results of Object.prototype.toString.call(algo) sane:

Object.prototype.toString.call([]); // [object Array]
Object.prototype.toString.call({}); // [object Object]
Object.prototype.toString.call(''); // [object String]
Object.prototype.toString.call(new Date()); // [object Date]
Object.prototype.toString.call(1); // [object Number]
Object.prototype.toString.call(function () {}); // [object Function]
Object.prototype.toString.call(/test/i); // [object RegExp]
Object.prototype.toString.call(true); // [object Boolean]
Object.prototype.toString.call(null); // [object Null]
Object.prototype.toString.call(); // [object Undefined]

However, in this case, there is no reason not to simply use

if(typeof callback !== 'function'){

... is simpler and semantically correct.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.