Created
February 18, 2010 15:02
-
-
Save lambder/307714 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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