filter, map, reduce

my attempt at creating those functions and learning how they work

by Mladen Mihajlovic

Babel + JSX

/**
 * predicate(accumulator, arrayItem) : accumulator
 */
function reduce(arr, predicate, initValue) {
	//initialise accumulator to the initial value
  let accumulator = initValue;

	// iterator over each item, 
  // send acuumulator and array item to predicate
  for (i = 0; i < arr.length; i++) {
    accumulator = predicate(accumulator, arr[i]);
  }

  // return the final accumulator
  return accumulator;
}

/**
 * predicate(arrayItem) : arrayItem
 */
function map(arr, predicate) {
	// call reduce where the initial value is an empty array,
  // and in the predicate push to the accumulator array, 
  // whatever the predicate returns
	return reduce(arr, (acc, i) => {
    let r = predicate(i);
  	acc.push(r);
    return acc;
    }, []);
}

/**
 * predicate(arrayItem) : bool
 */
function filter(arr, predicate) {
	// call reduce where the initial value is an empty array,
  // and if the predicate returns true, add the item
  // to the accumulator array
	return reduce(arr, (acc, i) => {
  	if (predicate(i)) acc.push(i);
    return acc;
  }, []);
}

// test array
let arr = [{
  name: 'Mladen',
  age: 40
}, {
  name: 'Dan',
  age: 21
}, {
  name: 'Tijana',
  age: 37
}];

// tests
let totalAge = reduce(arr, (acc, item) => acc = acc + item.age, 0);
console.log('Total Age (reduce): ',totalAge);

let names = map(arr, (i) => i.name);
console.log('Only Names (map):', names);

let over21 = filter(arr, (i) => i.age > 21);
console.log('Over 21 (filter):', over21);