Last Updated: February 25, 2016
·
1.496K
· daniel-hug

Sudo methods in JavaScript

Do you get tired of writing Array.prototype.slice.call(nodeList).forEach(fn) or Array.prototype.forEach.call(arguments, fn) just because the native array methods don't support collections other than arrays? Have no fear! Sudo methods to the rescue:

var sudo = (function(arr, obj) {
    [
        ['forEach', arr, 'each'],
        ['map', arr],
        ['indexOf', arr],
        ['filter', arr],
        ['hasOwnProperty', obj, 'has'],
        ['toString', obj]
    ].forEach(function(method) {
        var fn = method[1][method[0]];
        obj[method[2] || method[0]] = fn.call.bind(fn);
    });
    return obj;
})([], {});

This itty bitty script enables magic like this: sudo.each(nodeList, fn); or sudo.map(arguments, fn);. These work much like Underscore's and Lo-Dash's _.each and _.map functions.

The script also makes it easy to safely use methods of Object.prototype*:

function toType(val) {
    return sudo.toString(val).slice(8, -1).toLowerCase();
}
toType(true) //=> 'boolean'

var obj = { hasOwnProperty: function() {
    return false;
} };
obj.hasOwnProperty('hasOwnProperty')       //=> false :(
sudo.has(obj, 'hasOwnProperty') //=> true  :)

Feel free to add or exclude any methods you like for your own use. Here's the gist.

*Note that I'm not the genius that came up with toType()