I’m reading Functional Programming – Eloquent JavaScript at the moment.
// call function for each item
function forEach(items, fn) {
for (var i=0, ii=items.length; i<ii; i++) fn(items[i]);
}
// reduce an array to a single value by calling a function on each item and adding to a base value
function reduce(fn, base, array) {
forEach(array, function (item) {
base = fn(base, item);
});
return base;
}
// calls a function on each item in array
function map(fn, array) {
var result = [];
forEach(array, function (element) {
result.push(fn(element));
});
return result;
}
// creates an array from iterable items starting at an index
function asArray(items, start) {
var result = [];
for (var i=start || 0, ii=items.length; i<ii; i++) result.push(items[i]);
return result;
}
// define a new function that calls a fn with a list of arguments at the start pre-specified.
function partial(fn) {
var fixedArgs = asArray(arguments, 1);
return function() {
return fn.apply(null, fixedArgs.concat(asArray(arguments)));
}
}
// define a new function that calls fn1 and fn2 on the result.
function compose(fn1, fn2) {
return function() {
return fn2(fn1.apply(null, arguments)); // I switched the order around here, doesn't this make more sense?
};
}
Certain functions I see would be very useful:
forEach & map I would commonly write our with for loops and arrays but I see that I’ve been wasting a lot of time writing these loops by hand.
Any other functions like these you guys use regularly?