Functional programming method that allows you to call a worker function
// same worker function
function mapForEach(arr, fn) {
var newArr = [];
for (var i = 0; i < arr.length; i++) {
newArr.push(
fn(arr[i])
);
}
return newArr;
}
var arr1 = [1,2,3];
// check to see if limiter is greater than the item
var checkLimit = function(limiter, item){
return item > limiter;
}
// binds checkLimit to mapForEach to see if
// each array item is greater than the limiter above
// this sets the limiter to 1
// bind will allow 2 args -- there's only 1 in fn(arr[i])
var arr4 = mapForEach(arr1, checkLimit.bind(this, 1));
console.log(arr4) // => [false, true, true]
// same worker function
function mapForEach(arr, fn) {
var newArr = [];
for (var i = 0; i < arr.length; i++) {
newArr.push(
fn(arr[i])
);
}
return newArr;
}
var arr1 = [1,2,3];
// checks to see if limiter is greater
// but within a function expression to bind to mapForEach fn
var checkLimitSimple = function(limiter){
return function(limiter, item){
return item > limiter;
}.bind(this, limiter);
}
// this way limiter is already bound to newArr & we can just pass the limiter
var arr5 = mapForEach(arr1, checkLimitSimple(1));
console.log(arr5);function mapForEach(arr, fn) {
// empty array as a temp container
var newArr = [];
for (var i = 0; i < arr.length; i++) {
// add each item of arr1 to newArr
newArr.push(
fn(arr[i])
);
}
return newArr;
}
var arr1 = [1,2,3];
console.log(arr1); // => [1,2,3]
// will take arr1 push it into newArr, map each item into newArr
// and return each down here * 2
var arr2 = mapForEach(arr1, function(item){
return item * 2;
});
console.log(arr2); // => [2,4,6]
var arr3 = mapForEach(arr1, function(item){
return item > 2; // true if > 2
});
console.log(arr3); // => [false, false, true]