简体   繁体   中英

Checking for the return type of predicate

 Array.prototype.takeWhile = function (predicate) { 'use strict'; var $self = this if (typeof predicate === 'function') { let flagged = false, matching_count = 0, nomatching_count = 0; for (let i = 0; i < $self.length; i++) { let e = $self[i] if (predicate(e)) { if (!nomatching_count) { matching_count++ } else { flagged = true break } } else { nomatching_count++ } } return !flagged ? $self.slice(0, matching_count) : $self } throw new TypeError('predicate must be a function') }; var test = function () { var array = [1, 2, 3, 4, 5]; alert(array.takeWhile(x => x <= 3)) }; 
 <button onclick="test()">Click me</button> 

After the condition:

if (typeof predicate === 'function') {

}

I want to ask: how to check the return type of predicate ?

I want to prevent this case:

var array = [1, 2, 3, 4, 5];
alert(array.takeWhile(function () {}));

Javascript functions can return anything so there's no way of predicting or inferring their return type. The only way to determine the type of what's been returned is to run the function and check the type of the result.

var result = predicate(e);
if (typeof result === 'undefined') {
    throw 'Invalid predicate'
}

Notice that the return type of a function can be undefined , which is what an empty function will return.

However, this seems unnecessary since built in array methods don't have any check for this sort of edge case. For example [1,2,3].filter(function() {}); the Array.filter() method returns an empty array because the supplied function (predicate) never returns true against any items in the array.

 console.log( [1,2,3].filter(function() {}) ); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM