Basic Algorithm Scripting

**(1) Find the Longest Word in a String **

function findLongestWord(str) {
  var arr = str.split(" ");
  var lenArr = arr.map(function(val) {
    return val.length;
  });
  
  return Math.max.apply(null, arrNum);
}

findLongestWord("The quick brown fox jumped over the lazy dog");  // 输出6
findLongestWord("What is the average airspeed velocity of an unladen swallow")  // 输出8
findLongestWord("What if we try a super-long word such as otorhinolaryngology") // 输出19

(2) 字符串中每个单词的首字母大写

function titleCase(str) {
  var arr = str.toLowerCase().split(" ");
  var newArr = arr.map(function(val) {
    return val[0].toUpperCase() + val.substring(1, val.length);
  });
  return newArr.join(" ");
}


titleCase("I'm a little tea pot");  // 输出"I'm A Little Tea Pot"
titleCase("sHoRt AnD sToUt"); // 输出"Here Is My Handle Here Is My Spout"

(3) Return Largest Numbers in Arrays

function largestOfFour(arr) {
  var result = [];

  for (var i = 0; i < arr.length; i++) {
    var tempArr = arr[i];
    var tempVal = tempArr.reduce(function(preVal, curVal) {
      return curVal > preVal ? curVal : preVal;
    }, 0);

    result.push(tempVal);
  }
  return result;
}

largestOfFour([[13, 27, 18, 26], [4, 5, 1, 3], [32, 35, 37, 39], [1000, 1001, 857, 1]]) ;   //输出[27,5,39,1001]
largestOfFour([[4, 9, 1, 3], [13, 35, 18, 26], [32, 35, 97, 39], [1000000, 1001, 857, 1]]); // 输出 [9, 35, 97, 1000000]

(4)Caesars Cipher


function rot13(str) { // LBH QVQ VG!
  var arr = [];
  var myStr = '';
  for (var i = 0; i < str.length; i++) {
    var codeNum = str.charCodeAt(i);
    
    if ((codeNum >= 65) && (codeNum <= 77)) {
      
      myStr = String.fromCharCode(codeNum+13);
    
    } else if ((codeNum > 77) && (codeNum < 91)) {
    
      codeNum = 13 - (90-codeNum) + 64;
      myStr = String.fromCharCode(codeNum);
    
    } else {
    
      myStr = String.fromCharCode(codeNum);
    
    }
  
    arr.push(myStr);
  }
  return arr.join('');
}

rot13("SERR PBQR PNZC");  // 输出"FREE CODE CAMP"
rot13("SERR CVMMN!")  // 输出"FREE PIZZA!"
rot13("SERR YBIR?")   // 输出"FREE LOVE?"
rot13("GUR DHVPX OEBJA QBT WHZCRQ BIRE GUR YNML SBK.") // 输出"THE QUICK BROWN DOG JUMPED OVER THE LAZY FOX."

你可能感兴趣的:(Basic Algorithm Scripting)