Skip to content

Instantly share code, notes, and snippets.

@lambder
Created February 18, 2010 15:02
Show Gist options
  • Save lambder/307714 to your computer and use it in GitHub Desktop.
Save lambder/307714 to your computer and use it in GitHub Desktop.
// usage:
// var double = function(a){Functional.map(a, function{return 2*a})};
// double([1,2,3]) -> [2,4,6]
// var even = function(a){Functional.map(a, function{return a%2 == 0})};
// even([1,2,3,4,5,6,7]) -> [2,4,6]
var Functional = {
isFunction: function(obj) {
return toString.call(obj) === "[object Function]";
},
reduce: function(accumulator, object, callback) {
var name, i = 0,
length = object.length,
isObj = length === undefined || Functional.isFunction(object);
var acc = accumulator;
if (isObj) {
for (name in object) {
acc = callback.call(object[ name ], acc, object[ name ], name);
}
} else {
for (var value = object[0]; i < length; value = object[++i]) {
acc = callback.call(value, acc, value, i);
}
}
return acc;
},
map: function(object, callback) {
return Functional.reduce([], object, function(acc, index_key, value) {
var m = callback.call(value, value, index_key);
acc.push(m);
return acc;
});
},
filter: function(object, callback) {
var isObj = object.length === undefined || Functional.isFunction(object);
if (isObj) {
return Functional.reduce({}, object, function(acc, value, index_key) {
if(callback.call(value, value, index_key) !== false){
acc[index_key] = value;
}
acc.prototype = object.prototype;
return acc;
});
} else {
return Functional.reduce([], object, function(acc, value, index_key) {
if(callback.call(value, value, index_key) !== false){
acc.push(value);
}
return acc;
});
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment