Skip to content

Instantly share code, notes, and snippets.

@sagaban
Created August 13, 2016 16:07
Show Gist options
  • Save sagaban/3114a156cba3e34f9601bf10baac83ed to your computer and use it in GitHub Desktop.
Save sagaban/3114a156cba3e34f9601bf10baac83ed to your computer and use it in GitHub Desktop.
(function (/* 01. reduce (v, fn, b) */) {
var reduce = function (v, fn, b) {
return reduceAux (v, fn, b, 0, b);
};
var reduceAux = function (v, fn, b, p, ac){
return p > v.length - 1 ?
ac :
reduceAux(v, fn, b, p+1, fn(ac, v[p], p, v ));
};
var map = function (v, fn) {
return reduce (v, function (ac, e, i, v) {
return ac.concat (fn (e, i, v));
}, []);
};
/* //2
var map = function map (v, fn) {
return reduce(v, mapAux(v, fn), []);
}
var mapAux = function(v, fn ){
return function(ac, e, p, v ){
return ac.concat(fn (e, p, v));
}
};*/
//3 Doesn't work
/* var map = function map (v, fn) {
return reduce(v, mapAux.bind(this), []);
}
var mapAux = function(ac, e, p, v ){
return ac.concat(this.fun(e, p, v));
};*/
var add = function (x, y) { return x + y; };
var mul = function (x, y) { return x * y; };
var odd = function (x, y) { return !y; };
var cnt = function (x, y) { return y+1; };
console.log (
reduce ([1,2,3,4,5], add, 0), // 15
reduce ([1,2,3,4,5], mul, 1), // 120
reduce ([1,2,3,4,5], odd, true), // false
reduce ([1,2,3,4,5], cnt, 0) // 6
);
console.log (
map ([1,2,3,4,5], function (x){ return -x; }), // [ -1, -2, -3, -4, -5 ]
map ([1,2,3,4,5], function (x){ return x*x; }) // [ 1, 4, 9, 16, 25 ]
);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment