Skip to content

Instantly share code, notes, and snippets.

@karlpokus
Last active December 13, 2016 14:14
Show Gist options
  • Save karlpokus/fbed52b8863123197d379149ec9387c5 to your computer and use it in GitHub Desktop.
Save karlpokus/fbed52b8863123197d379149ec9387c5 to your computer and use it in GitHub Desktop.
JS filter, map and reduce - homemade
// MAPPY
Array.prototype.mappy = function(fn, that) {
var out = [],
x,
that = that || {};
for (var i = 0; i < this.length; i++) {
x = fn.call(that, this[i], i, this);
out.push(x);
}
return out;
};
// FILTERY
Array.prototype.filtery = function(fn, that) {
var out = [],
flag,
that = that || {};
for (var i = 0; i < this.length; i++) {
flag = fn.call(that, this[i], i, this);
if (flag) {
out.push(this[i]);
}
}
return out;
}
// REDUCY
Array.prototype.reducy = function(fn, initial){
var res,
accumulator,
i = (initial)? 0: 1;
for (i; i < this.length; i++) {
accumulator = fn.call(
this,
accumulator || initial || this[i-1],
this[i],
i,
this
);
}
return accumulator;
}
var data = [
{id: 1, name: 'mike', power: 12},
{id: 2, name: 'julia', power: 10},
{id: 3, name: 'troy', power: 5},
{id: 4, name: 'sarah', power: 2},
{id: 5, name: 'truls', power: 8}
];
var res = data
.filtery(function(o){
return o.id > 2;
})
.mappy(function(o){
return o.power;
})
.reducy(function(base, item){
return base + item;
});
console.log(res);
// DEMO at http://codepen.io/KarlPokus/pen/oXQrWg?editors=0012
@karlpokus
Copy link
Author

Update reducy to include correct default for initial value as 2nd arg and all the args to the callback. Kinda terse but simple enough to read me thinks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment