Last Updated: February 25, 2016
· daniel-hug

Sudo methods in JavaScript

Do you get tired of writing or, 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]] =;
    return obj;
})([], {});

This itty bitty script enables magic like this: sudo.each(nodeList, fn); or, fn);. These work much like Underscore's and Lo-Dash's _.each and 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()