Skip to content

Instantly share code, notes, and snippets.

@lambder
Created March 9, 2010 07:14
Show Gist options
  • Save lambder/326327 to your computer and use it in GitHub Desktop.
Save lambder/326327 to your computer and use it in GitHub Desktop.
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) {
if(object.hasOwnProperty(name))
acc = callback.call(object, acc, object[ name ], name);
}
} else {
for (var value = object[0]; i < length; value = object[++i]) {
acc = callback.call(object, acc, value, i);
}
}
return acc;
},
map: function(object, callback) {
return Functional.reduce([], object, function(acc, value, index_key) {
var m = callback.call(object, value, index_key);
acc.push(m);
return acc;
});
},
each: function(object, callback) {
return Functional.reduce(null, object, function(acc, value, index_key) {
callback.call(object, value, index_key);
return null;
});
},
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(object, value, index_key)){
acc[index_key] = value;
}
return acc;
});
} else {
return Functional.reduce([], object, function(acc, value, index_key) {
if(callback.call(object, value, index_key)){
acc.push(value);
}
return acc;
});
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment