Skip to content

Instantly share code, notes, and snippets.

@ivan-ha
Created March 2, 2017 14:04
Show Gist options
  • Save ivan-ha/22077f7e8ba2163d406c2fd2dc3345bf to your computer and use it in GitHub Desktop.
Save ivan-ha/22077f7e8ba2163d406c2fd2dc3345bf to your computer and use it in GitHub Desktop.
Functional programming in js
function mapForEach(array, fn) {
var tmpArr = [];
for (var i = 0; i < array.length; i++) {
tmpArr.push(
fn(arr[i])
);
}
return tmpArr;
}
var arr1 = [1, 2, 3];
var arr2 = mapForEach(arr1, function(item) {
return item * 3;
});
var arr3 = mapForEach(arr1, function(item) {
return item > 2;
});
var largerThan = function(limit, item) {
return item > limit;
};
var arr4 = mapForEach(arr1, largerThan.bind(this, 1)); // passing limit as 1 using .bind()
var largerThanSimplified = function(lim) {
return function(limit, item) {
return item > limit;
}.bind(this, lim);
};
var arr5 = mapForEach(arr1, largerThanSimplified(2));
console.log(arr1); // [1, 2, 3]
console.log(arr2); // [3, 6, 9]
console.log(arr3); // [false, false, true]
console.log(arr4); // [false, true, true]
console.log(arr5); // [false, false, true]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment