Typescript Algorithms

Answers to common problems using Typescript.

Parentheses Closer

Write a function to add parentheses so that all opening and closing parentheses (brackets) have matching counterparts. You will do this by appending parenthesis to the beginning or end of the string. The result should contain the original string, and be of minimal length.

const addParens = (inputString: string): string => {
  // create local vars
  let neededToCloseParens = 0;
  const openingParen = "(";
  const closingParen = ")";

  // instantiate our input and return objects
  const inputStringArray = inputString.split("");
  const returnStringArray: Array<string> = [];

  // loop through string array
  for (let i = 0; i < inputStringArray.length; i++) {
    // if we have opening bracket, push it no matter what
    if (inputStringArray[i] === openingParen) {
      returnStringArray.push(inputStringArray[i]);
      // else check for closing paren and increment needed closing parens
    } else if (inputStringArray[i] === closingParen) {
      if (!returnStringArray.pop()) neededToCloseParens++;
    }
  }

  // create arrays from counters, join to create strings
  const openingParensArray = Array(neededToCloseParens + 1).join(openingParen);
  const closingParensArray = Array(returnStringArray.length + 1).join(
    closingParen
  );

  // concatenate our final string, remove commas with regex
  return (openingParensArray + inputStringArray + closingParensArray).replace(
    /,/g,
    ""
  );
};

Simple Palindrome Checker

Return true if input is palindrome, false if not.

const isPalendrome = (inputString: string): boolean => {
  const revString = inputString.split('').reverse().join('');
  return revString === str;
};

Simple Anagram Checker

Return true if input strings are anagrams of each other.

const isAnagram = (aString: string, bString: string): boolean => {
  return aString.split('').sort().join('') === bString.split('').sort().join('');
};

Simple Array Flatten

Return single array from array of arrays.

const flattenArray = (inputArrays: Array<any>): Array<any> => {
  return inputArrays.reduce((arrayA: Array<any>, arrayB: Array<any>) => {
    return arrayA.concat(arrayB);
  });
};

Longest Word of a Sentence

Determine longest word (or words if there is a tie in length) from input sentence string

const getLongestWord = (sentence: string): string | Array<string> => {
  const wordArr = sentence.toLowerCase().match(/[a-z0-9]+/g);
  const sorted = wordArr.sort((a: string, b: string) => b.length - a.length);
  
  // if multiple words, insert into array
  const longestWordArr = sorted.filter((word: string) => word.length === sorted[0].length);
  
  // Check if more than one array value
  if (longestWordArr.length === 1) {
     return longestWordArr[0];
  } else {
     return longestWordArr;
  }
};

Classic "FizzBuzz"

Loop from start to finish number. For multiples of 3, instead of the number, print "Fizz". For multiples of 5, print "Buzz". For multiples of both 3 and 5, return "FizzBuzz".

const printFizzBuzzToConsole = (start: number, end: number): string => {
  let returnStr: string = '';
  
  for (let i = start; i <= end; i++) {
     if (i % 15 === 0) {
       returnStr += 'FizzBuzz';
     } else if (i % 3 === 0) {
       returnStr += 'Fizz';
     } else if (i % 5 === 0) {
       returnStr += 'Buzz';
     }
  }
  
  return returnStr;
};

Capitalize First Letter of Each Word

Return a string with each word having the first letter capitalized from an input string sentence.

const capitalizeEachFirstLetter = (inputString: string): string => {
  // split on words, not letters by using ' '
  const strArr = inputString.toLowerCase().split(' ');
  
  for (let i = 0; i < strArr.length; i++) {
    strArr[i] = strArr[i].substring(0, 1).toUpperCase() + strArr[i].substring(1);
  }
  
  // re-create the sentence
  return strArr.join(' ');
};

Vowel Checker

Check if letter is a vowel, return a boolean.

const isVowelLetter = (letter: string): boolean => {
  if (typeof letter !== 'string')
    return false;
  
  const returnArr = letter.match(/[aeiou]/gi);
  return returnArr && returnArr.length > 0;
};

Sum Array of Numbers

Return sum from array of numbers.

const sumNumbersFromArray = (numbersArray: Array<number>): number => {
  let result: number = 0;
  for (const number of numbersArray) {
    result += number;
  }
  return result;
};

Sum all prime numbers

Loop using input number as max, sum all prime numbers in that range.

const isPrimeNumber = (num: number): boolean => {
  // numbers greater than 1 are prime
  for (let i = 2; i < num; i++) {
    if (num % i === 0) {
      return false;
    }
  }
  return true;
}

const sumPrimeNumbers = (num: number): number => {
  let total: number = 0;
  
  for (let i = 2; i <= num; i++) {
    if (isPrimeNumber(i)) {
      total += i;
    }
  }
  
  return total;
}

Seek and Destroy

Filter an input array based on an array of remove values.

const seekAndDestroy = (
  inputArr: Array<any>,
  removeArr: Array<any>
): Array<any> => {
  return inputArr.filter((item: any) => !removeArr.includes(item));
};

Array sort while ignoring positions

Sort an array, ignoring certain items if input condition is met.

const smartArraySort = (inputArr: Array<any>, itemsToKeep: Array<any>): Array<any> => {
  const keepIndexes: Array<any> = [];
  const itemsArray: Array<any> = [];
  inputArr.forEach((item: any, index: number) => {
    if (itemsToKeep.includes(item)) {
      keepIndexes.push(index);
    } else {
      itemsArray.push(item);
    }
  });
  return itemsArray.sort((a : any, b : any) => a - b);
};

Missing Letters

Find the missing letter in the passed range and return it. Return undefined if entire alphabet passed.

const missingLetters = (alphabetStr: string): Array<string> | undefined => {
  let compareChar: number = alphabetStr.charCodeAt(0);
  const missing: Array<string> = [];
  const sortedStrArr: Array<string> = alphabetStr.split('').sort();

  // create letter array, check against charCode
  sortedStrArr.forEach((_char: string, index: number) => {
    if (alphabetStr.charCodeAt(index) === compareChar) {
      ++compareChar;
    } else {
      const missingLetter: string = String.fromCharCode(compareChar);
      if (!missing.includes(missingLetter))
      missing.push(missingLetter);
    }
  });
  return missing;
};