Basic algorithm scripting

Reverse a string

function reverseString(str) {
  var myArray = [];
  var myString = str;
  myArray = myString.split('');
  myArray = myArray.reverse();
  myString = myArray.join('');
  return myString;
}
reverseString("hello");

Factorialize a number

function factorialize(num) {
  var a=1;
  for (i=num; i > 1; i--) {
    a = a*(i-1);
  }
  return a;
}
factorialize(5);

Check for Palidromes

function palindrome(str) {
  // Good luck!
  
  
  var myString = "";
  var myOtherString = "";
  var myArray = [];
  var myOtherArray = [];
  
  myString = str.toLowerCase();
  myOtherString = myString.replace(/[^abcdefghijklmnopqrstuvwxyz1234567890]/g,''); // remove non-alphanumeric characters
  myArray = myOtherString.split('');
  myOtherArray = myArray.slice(0);  // lets clone the array
  myOtherArray.reverse();
  
  for (var i = 0, l=myArray.length; i < l; i++) {
     if (myArray[i] != myOtherArray[i]) { 
       return false; 
     }
  }
  return true; 
}
palindrome("eye");

Find the longest word in a string

function findLongestWord(str) {

  var myArray = [];
  
  myArray = str.split(' ');
  var longestWord = myArray[0];
  
  for (var i=0; i < myArray.length; i++) {
    
    if (longestWord.length < myArray[i].length) {
      longestWord = myArray[i];
    }
  }
  
  return longestWord.length;
}

findLongestWord("The quick brown fox jumped over the lazy dog");

Title Case a sentence

function titleCase(str) {
  
   var myArray = str.split(" "); // move the words to an array
   var myOtherArray = [];  // we'll use this to construct the correctly capitalized sentence
  
   for (var i = 0; i < myArray.length; i++) {
     
      var myString = myArray[i].toLowerCase();        
      myString = myString.charAt(0).toUpperCase() + myString.substring(1);
      myOtherArray.push(myString);
   }
  
   return myOtherArray.join(" ");
  
} 

titleCase("I'm a little tea pot");

Return largest number in arrays

function largestOfFour(arr) {
  // You can do this!
  
  var myArray = [];
  for (var i = 0; i < arr.length; i++) {
    
    myArray[i] = arr[i][0];
    for (var x = 0; x < arr[i].length; x++); {
      
      if (myArray[i] < arr[i][x+1]) {
        myArray[i] = arr[i][x+1];
      }
    }
  }
  
  return myArray;
}

largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);

Confirm the ending

function confirmEnding(str, target) {
  // "Never give up and good luck will find you."
  // -- Falcor
  
  
  // My original answer commented out below .. 
  // Then I found the one liner solution when 
  // reading through the friendly manual. It
  // doesn't work with IE or Opera but it's so *neat*!
  
  /*
  var firstLength = str.length;
  var secondLength = target.length;
  
  if (secondLength > firstLength) { return false; }
  
  var temp = str.substr(firstLength-secondLength);
  if (temp == target) { return true; }
  
  return false;
  */

  return str.endsWith(target);
   
}

confirmEnding("Bastian", "n");

Repeat a string repeat a string

function repeatStringNumTimes(str, num) {
  // repeat after me
  
  if (num < 1) { return ""; }
  
  str = str.repeat(num);
  
  return str;
}
repeatStringNumTimes("abc", 3);

Truncate a string

function truncateString(str, num) {
  // Clear out that junk in your trunk
  
  if (num <= 3) {
    
    str = str.slice(0, num) + "...";
    return str;
  }
  
  if (num >= str.length) {
    return str;
  }
  
  num -= 3;
  str = str.slice(0, num) + "...";
  
  return str;
}
truncateString("A-tisket a-tasket A green and yellow basket", 11);

Chunky Monkey

function chunkArrayInGroups(arr, size) {
  // Break it up.

  var myArray = [];
  var sets = arr.length/size;

  for (var i = 0; i < sets; i++) {
   if (arr[0] === undefined) { break; } // for sets that don't divide neatly
    myArray.push(arr.splice(0, size));
  }

  return myArray;
}
chunkArrayInGroups([0, 1, 2, 3, 4, 5], 2);

Slasher Flick

function slasher(arr, howMany) {
  // it doesn't always pay to be first

  arr.splice(0,howMany);
  
  return arr;
}
slasher([1, 2, 3], 2);

Mutations

function mutation(arr) {
 
  // pull the letters from second string and sort them
  var firstString = arr[0].slice();
  var secondString = arr[1].slice();
  
  firstString = firstString.toLowerCase();
  secondString = secondString.toLowerCase();
  
  for (i = 0; i < secondString.length; i++) {
    
    if (firstString.indexOf(secondString.charAt(i)) < 0) { return false; }
    
  }
  
  return true;
}


mutation(["hello", "Hello"]);

Falsy Bouncer

function bouncer(arr) {
  // Don't show a false ID to this bouncer.
 
  function isFalsy(value) {
    if (value === false)     { return false; }
    if (value === null)      { return false; }
    if (value === 0)         { return false; }
    if (value === "")        { return false; }
    if (Number.isNaN(value)) { return false; }
    if (value === undefined) { return false; }
    
    return true;
    
}
var id = arr.filter(isFalsy);
   
  return id;
}

bouncer([7, "ate", "", false, 9]);

Seek and Destroy

function destroyer(arr) {
  // Remove all the values
  
  var myOtherArray = [];
   
  myOtherArray = Array.from(arguments);  // get *all* arguments passed on to the function, including the original array
  myOtherArray.shift();  // lets drop the first element (aka the array)
  
  function isGoodValue(value) {
  
    for (var i = 0; i < myOtherArray.length; i++) {
      // now lets compare the passed array value to the naughty list
      
      if (value == myOtherArray[i]) { return false; }
    
      }
  
    return true;
  
   }
  
  var filtered = arr.filter(isGoodValue);  // this steps through every value in the array and drops it if the function returns false

  return filtered;
}
destroyer([1, 2, 3, 1, 2, 3], 2, 3);

Where do I belong

function getIndexToIns(arr, num) {
  // Find my place in this sorted array.

  function compareNumbers(a, b) {
    return a - b;
  }
  
  var pointer = 0;
  arr.sort(compareNumbers);   // Needed because, e.g. '10' comes before '2' in Unicode code point order.
  
  for (var i = 0; i < arr.length; i++) {
    
    if (arr[i] >= num) { pointer = i; break; }
    
    pointer = arr.length;   // if the num is the largest in the array, so the above comparison never triggers.
    
  }
   
  return pointer;
}  
getIndexToIns([5, 3, 20, 3], 5);

Caesars Cipher

function rot13(str) { // LBH QVQ VG!

// 'A' is 65, 'Z' is 90
// from 'M' (which is 78) we need 
// to roll back to the beginning.


var myArray = [];
var myOtherArray = [];


myArray = str.split('');

for (var i = 0; i < myArray.length; i++) {

  
  if (str.charCodeAt(i) < 65 || str.charCodeAt(i) > 90) {  // is this outside the A-Z range? If so, pass it on without rotation.
    myArray[i] = str.charCodeAt(i);
  }
  
  else if (str.charCodeAt(i) < 78) {
    myArray[i] = str.charCodeAt(i)+13;
  }

  else {
    myArray[i] = str.charCodeAt(i)-13;
  }
  
}

   
for (var x = 0; x < myArray.length; x++) {
   
  var z = myArray[x];
  myOtherArray[x] = String.fromCharCode(z);
  
}

str = myOtherArray.join("");

return str;

}

// Change the inputs below to test
rot13("SERR PBQR PNZC");
Last modified: le 2016/05/17 11:59