WEB818
11/2/2019 - 7:51 PM

reduce method on string and numbers

//.reduce() method to add items in array and decode string of text
//SYNTAX: arr.reduce(callback(accumulator, currentValue[, index[, array]])[, initialValue])
let text = 'noggin oreo the moon time tele steed his tent apollo her lives though shoo tofu budapest';
let numbers = [1,2,3,4,5,6];

function reduceNum(numArr) {
  const reducer = (acc, currentValue) => acc + currentValue;
  console.log(`This function returns sum of ${numArr.reduce(reducer)}`);

  //better to run function and console log the variable assigned to the function
  const numberSum = numArr.reduce((acc, currentValue) => acc + currentValue);
  console.log(`This is a cleaner way to execute reduce method: sum = ${numberSum}`);
}

reduceNum(numbers);

function makeStrArr(textStr) {
  let strArr = textStr.split(' ');
  const decoded = strArr.reduce((decodedString, word) => {
    if (word.length === 3) {
      return decodedString + ' ';
    } else {
      return decodedString + word[word.length-1].toUpperCase();
    }
  }, '');
  console.log(decoded);
}

makeStrArr(text);