Skip to content

Instantly share code, notes, and snippets.

@nubunto
Last active December 30, 2015 12:39
Show Gist options
  • Select an option

  • Save nubunto/7830734 to your computer and use it in GitHub Desktop.

Select an option

Save nubunto/7830734 to your computer and use it in GitHub Desktop.
map/reduce/each functionality, with a example.
var type, each, filter, map, reduce;
type = function (arg) {
//filter out the type of the object, by getting the [[Class]] property.
return Object.prototype.toString.call(arg).slice(8, -1).toLowerCase();
};
each = function (arg, fn) {
var typef = type(arg); // get the type of the argument, but the real one.
var i, len = (arg && arg.length), value;
if(typef === 'array') { //if we're seeing an array,
for (i = 0, len = arg.length; i < len; i++) {
value = fn.call(arg, arg[i], i); //just use the function
if (value === false) break;
}
} else { //else, loop as an object.
for (i in arg) {
value = fn.call(arg, arg[i], i);
if (value === false) break;
}
}
return arg;
};
map = function (array, fn) {
//the returned array.
var newArray = [];
each(array, function (val) {
//push the value the function returns into the array.
newArray.push(fn.call(array, val));
});
//return it.
return newArray;
};
filter = function (array, fn) {
//the filtered elements.
var filtered = [];
each(array, function (val) {
var value = fn.call(array, val);
if (value === true) { //if the element passes the criteria,
filtered.push(val); //add it to the filtered elements.
}
});
//return it.
return filtered;
};
reduce = function (array, fn, base) {
var ret = base; //start the return value with the base.
each(array, function (val) {
ret = fn.call(array, ret, val); //glue it with the elements that were passed from the function
});
//return the summed up result.
return ret;
};
//compute the average age of these adults.
var testArray = [
{name: 'john', age: 21},
{name: 'sammy', age: 15},
{name: 'barbara', age: 45},
{name: 'ferris', age: 67}
];
//contabilize the adult ages.
var adultAges = //map the ages that are less than 18, but first,
map(
//filter out the ones below 18
filter(
testArray, function (person) {
return person.age >= 18;
}
),
//and then map over the resulting set to make an array of just ages.
function (person) {
return person.age;
}
);
//calculate the average, or, in other words, sum up all the ages, and then divide them by the total of ages.
var averageAge = Math.round(
reduce(
adultAges, function (base, age) {
return base + age;
}, 0 //start with 0.
) / adultAges.length
); // round up everything, and we have 44.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment