bebraw
5/10/2011 - 7:08 AM

map, filter and reduce for JS. Readable versions. Not guaranteed to work "fast".

map, filter and reduce for JS. Readable versions. Not guaranteed to work "fast".

var reduce = function(cb, seq) {
    var ret = seq[0];
    
    for(var i = 1, len = seq.length; i < len; i++) {
        ret = cb(ret, seq[i]);
    }
    
    return ret;
}
var map = function(cb, seq) {
    var ret = [];
    
    for(var i = 0, len = seq.length; i < len; i++) {
        ret.push(cb(seq[i], i));
    }
    
    return ret;
}
var filter = function(cb, seq) {
    var ret = [];
    
    for(var i = 0, len = seq.length; i < len; i++) {
        var item = seq[i];
        
        if(cb(item, i)) {
            ret.push(item);
        }
    }
    
    return ret;
}
var _ = function(seq) {
    var value = seq;
    var funcs = {
        map: map,
        filter: filter,
        reduce: reduce
    };
    var wrappedFuncs;
    
    var wrapFunctions = function() {
        var ret = {};

        var addFunction = function(name, func) {
            ret[name] = function() {
                value = func.call(this, arguments[0], value);

                return wrappedFuncs;
            };       
        };

        for(var name in funcs) {
            var func = funcs[name];

            addFunction(name, func);
        }

        ret.val = function() {
            return value;
        };

        return ret;
    };

    wrappedFuncs = wrapFunctions();
    
    return wrappedFuncs;
};