Reducer

by jessekinsman

HTML

<script src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/3.5.0/lodash.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.2/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.2/react-dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.3.4/jasmine.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.3.4/jasmine-html.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.3.4/jasmine.css">
<link rel="stylesheet" href="https://codepen.io/btholt/pen/WrwzJZ.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.3.4/boot.js"></script>
<div id='target'>no snapshots</div>

Babel + JSX

/*
  Reduce
  
  Good for taking a list and reducing it down to one value in a user defined way.
  
  Test 1
  Name your function addTogether
  Take in a list and return the result of that list added together
  Do not use a loop
  
  Test 2
  Name your function concatenateStringsWithSpaces
  Take in a list, return that string with those strings concatenated together with spaces between them
  Don't worry about leading or trailing whitespace
  Do not use .join or loops
  
  Test 3
  Name your function squaresAndSubtracts
  Map over your list, square each value, and then subtract them in order (take index 0, subtract index 1, 
  then index 2, etc.)
  Do not use a loop
  
  Test 4
  Name your function myReduce
  Implement your own reduce
  myReduce takes three parameters: the list being operated on, a function to apply the reduction, and 
  seed value to start the reduce
  You will need to use a loop
  
*/
const add = (accumulator, item) => item + accumulator;  
const addTogether = (list) => list.reduce(add);

const merge = (accumulator, item, seed) => accumulator + " " + item;
const concatenateStringsWithSpaces = (list) => list.reduce(merge);

const square = (item) => item * item;
const subtract = (accum, item) => accum - item; 
const squaresAndSubtracts = (list) => {
	let newList = list.map(square);
  return newList.reduce(subtract);
}

const myReduce = (list, func, seed) => {
	let accum = seed;
	for (let i = 0; i< list.length; i++) {
  	accum = func(accum, list[i]);
  }
  return accum;
}








// unit tests
// do not modify the below code
describe('reduce', function() {
  it('addTogether', () => {
    const testList = [5,3,0,7,2,5,6,10,9]
    expect(addTogether(testList)).toEqual(47);
  });
  it('concatenateStringsWithSpaces', () => {
    const testList = ['this', 'is', 'so', 'fun'];
    expect(concatenateStringsWithSpaces(testList).trim()).toEqual('this is so fun');
  });
  it('squaresAndSubtracts', () => {
    const testList = [10, 5, 4, 2, 1];
   ...