Code Snippets

Useful code snippets for use in your next web application. Everything from Typescript, useful array methods, API paginating functions, SCSS, etc.

STRING
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.
1const addParens = (inputString: string): string => {
2// create local vars
3let neededToCloseParens = 0;
4const openingParen = "(";
5const closingParen = ")";
6
7// instantiate our input and return objects
8const inputStringArray = inputString.split("");
9const returnStringArray: Array<string> = [];
10
11// loop through string array
12for (let i = 0; i < inputStringArray.length; i++) {
13  // if we have opening bracket, push it no matter what
14  if (inputStringArray[i] === openingParen) {
15    returnStringArray.push(inputStringArray[i]);
16    // else check for closing paren and increment needed closing parens
17  } else if (inputStringArray[i] === closingParen) {
18    if (!returnStringArray.pop()) neededToCloseParens++;
19  }
20}
21
22// create arrays from counters, join to create strings
23const openingParensArray = Array(neededToCloseParens + 1).join(openingParen);
24const closingParensArray = Array(returnStringArray.length + 1).join(
25  closingParen
26);
27
28// concatenate our final string, remove commas with regex
29return (openingParensArray + inputStringArray + closingParensArray).replace(
30  /,/g,
31  ""
32);
33};
STRING
Simple Palindrome Checker
Return true if input is palindrome, false if not.
1const isPalindrome = (inputString: string): boolean => {
2    const revString = inputString.split('').reverse().join('');
3    return revString === str;
4};
STRING
Simple Anagram Checker
Return true if input strings are anagrams of each other.
1const isAnagram = (aString: string, bString: string): boolean => {
2    return aString.split('').sort().join('') === bString.split('').sort().join('');
3};
ARRAY
Simple Array Flatten
Return single array from array of arrays.
1const flattenArray = (inputArrays: Array<any>): Array<any> => {
2    return inputArrays.reduce((arrayA: Array<any>, arrayB: Array<any>) => {
3        return arrayA.concat(arrayB);
4    });
5};
STRING
Find Longest Word of a Sentence
Determine longest word (or words if there is a tie in length) from input sentence string.
1const getLongestWord = (sentence: string): string | Array<string> => {
2    const wordArr = sentence.toLowerCase().match(/[a-z0-9]+/g);
3    const sorted = wordArr.sort((a: string, b: string) => b.length - a.length);
4    
5    // if multiple words, insert into array
6    const longestWordArr = sorted.filter((word: string) => word.length === sorted[0].length);
7    
8    // Check if more than one array value
9    if (longestWordArr.length === 1) {
10       return longestWordArr[0];
11    } else {
12       return longestWordArr;
13    }
14};
STRING
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.
1const printFizzBuzzToConsole = (start: number, end: number): string => {
2    let returnStr: string = '';
3    
4    for (let i = start; i <= end; i++) {
5       if (i % 15 === 0) {
6         returnStr += 'FizzBuzz';
7       } else if (i % 3 === 0) {
8         returnStr += 'Fizz';
9       } else if (i % 5 === 0) {
10         returnStr += 'Buzz';
11       }
12    }
13    
14    return returnStr;
15};
STRING
Capitalize First Letter of Each Word
Return a string with each word having the first letter capitalized from an input string sentence.
1const capitalizeEachFirstLetter = (inputString: string): string => {
2    // split on words, not letters by using ' '
3    const strArr = inputString.toLowerCase().split(' ');
4    
5    for (let i = 0; i < strArr.length; i++) {
6      strArr[i] = strArr[i].substring(0, 1).toUpperCase() + strArr[i].substring(1);
7    }
8    
9    // re-create the sentence
10    return strArr.join(' ');
11};
STRING
Vowel Checker
Check if letter is a vowel, return a boolean.
1const isVowelLetter = (letter: string): boolean => {
2    if (typeof letter !== 'string')
3      return false;
4    
5    const returnArr = letter.match(/[aeiou]/gi);
6    return returnArr && returnArr.length > 0;
7};
NUMBER
Sum Array of Numbers
Return sum from array of numbers.
1const sumNumbersFromArray = (numbersArray: Array<number>): number => {
2    let result: number = 0;
3    for (const number of numbersArray) {
4      result += number;
5    }
6    return result;
7};
NUMBER
Sum All Prime Numbers
Loop using input number as max, sum all prime numbers in that range.
1const isPrimeNumber = (num: number): boolean => {
2    // numbers greater than 1 are prime
3    for (let i = 2; i < num; i++) {
4      if (num % i === 0) {
5        return false;
6      }
7    }
8    return true;
9}
10
11const sumPrimeNumbers = (num: number): number => {
12    let total: number = 0;
13    
14    for (let i = 2; i <= num; i++) {
15      if (isPrimeNumber(i)) {
16        total += i;
17      }
18    }
19    
20    return total;
21}
ARRAY
Seek and Destroy
Filter an input array based on an array of remove values.
1const seekAndDestroy = (
2    inputArr: Array<any>,
3    removeArr: Array<any>
4): Array<any> => {
5    return inputArr.filter((item: any) => !removeArr.includes(item));
6};
ARRAY
Array Sort While Ignoring Positions
Sort an array, ignoring certain items if input condition is met.
1const smartArraySort = (inputArr: Array<any>, itemsToKeep: Array<any>): Array<any> => {
2    const keepIndexes: Array<any> = [];
3    const itemsArray: Array<any> = [];
4    inputArr.forEach((item: any, index: number) => {
5        if (itemsToKeep.includes(item)) {
6            keepIndexes.push(index);
7        } else {
8            itemsArray.push(item);
9        }
10    });
11    return itemsArray.sort((a : any, b : any) => a - b);
12};
STRING
Missing Letters
Find the missing letter in the passed range and return it. Return undefined if entire alphabet passed.
1const missingLetters = (alphabetStr: string): Array<string> | undefined => {
2    let compareChar: number = alphabetStr.charCodeAt(0);
3    const missing: Array<string> = [];
4    const sortedStrArr: Array<string> = alphabetStr.split('').sort();
5    
6    // create letter array, check against charCode
7    sortedStrArr.forEach((_char: string, index: number) => {
8      if (alphabetStr.charCodeAt(index) === compareChar) {
9        ++compareChar;
10      } else {
11        const missingLetter: string = String.fromCharCode(compareChar);
12        if (!missing.includes(missingLetter))
13        missing.push(missingLetter);
14      }
15    });
16    return missing;
17};
API
Real-world API Filtering & Pagination Example
Filter and paginate data based on data keys, and pagination values.
1const MOCK_GET_ENDPOINT = 'http://my-api-endpoint/v1/object';
2
3app.get(MOCK_GET_ENDPOINT, (req, res) => {
4  // assuming an array of data
5  const data = getData();
6 
7  try {
8    // query string object
9    const queryParams = req.query;
10    
11    // pagination
12    const ignoreParams = ["pageIndex", "pageSize"];
13    const pageIndex = queryParams.pageIndex
14      ? parseInt(queryParams.pageIndex)
15      : 0;
16    const pageSize = queryParams.pageSize
17      ? parseInt(queryParams.pageSize)
18      : 10;
19 
20    // calculate the start and end indexes for the requested page
21    const startIndex = pageIndex * pageSize;
22    const endIndex = (pageIndex + 1) * pageSize;
23 
24    // ignore pagination params
25    const filteredKeys = Object.keys(queryParams)
26      .filter((key) => !ignoreParams.includes(key))
27      .reduce((obj, key) => {
28        obj[key] = data[key];
29        return obj;
30      }, {});
31 
32    const filteredData = data.filter((message) => {
33      let isValid = true;
34      for (key in filteredKeys) {
35        // looser search, === will not work
36        isValid = isValid && message[key] == queryParams[key];
37      }
38      return isValid;
39    });
40 
41    // Slice the array based on the indexes
42    const paginatedData = filteredData.slice(startIndex, endIndex);
43 
44    // // Send the paginated data and total pages as the API response
45    res.json({
46      data: paginatedData,
47      count: filteredData.length,
48    });
49  } catch (err) {
50    res.send(err.message);
51  }
52});
NUMBER
Simple Currency Formatter
Format number to USD - Ex: 30000 to $30,000.00
1export const formatToUSD = (inputCurrency: number): string | undefined => {
2  const USDollar = new Intl.NumberFormat('en-US', {
3    style: 'currency',
4    currency: 'USD'
5  });
6 
7  if (!inputCurrency) return;
8 
9  return USDollar.format(inputCurrency);
10};
DATE
Simple Date Formatter
Using locale string, format date without using moment or similar.
1export const formatDate = (rawDate: string, localeString = 'en-US'): string => {
2  return new Date(rawDate).toLocaleDateString(localeString);
3};
NUMBER
Get Pagination Indexes From Page Count
Useful for pagination components, generate an array of available page indexes.
1export const getPageIndexesArray = (totalPages: number): Array<number> => {
2  return totalPages > 1 ? Array.from(Array(totalPages).keys()) : [0];
3};
STRING
Get Object From Query String
Convert query string params to object key: value pairs.
1export const getObjectFromQueryString = (searchString: string) => {
2  if (!searchString) return;
3  return JSON.parse(
4    '{"' +
5      searchString.replace('?', '').replace(/&/g, '","').replace(/=/g, '":"') +
6      '"}',
7    function (key: string, value: string) {
8      return key === '' ? value : decodeURIComponent(value);
9    }
10  );
11};
STRING
Simple Text Truncation with Ellipsis
Basic function to shorten text and add a '...'
1export const truncate = (
2  inputString: string,
3  length: number
4): string | undefined => {
5  // failsafe
6  if (!inputString || !length) return;
7 
8  return inputString.length > length
9    ? `${inputString.substring(0, length)}...`
10    : inputString;
11};
STRING
Remove Quotes
Simple function to remove any single or double quotes from a string.
1export const removeQuotes = (input: string): string => {
2    return input.replace(/['"]+/g, '');
3};
STRING
Camel Case to Words
Convert a camelCase string to Title Case.
1export const camelCaseToWords = (inputString: string): string | undefined => {
2  // failsafe
3  if (!inputString) return;
4 
5  const result = inputString.replace(/([A-Z])/g, ' $1');
6  return result.charAt(0).toUpperCase() + result.slice(1);
7};
STRING
Snake Case to Words
Convert a snake-case string to Title Case
1export const slugToWords = (slug: string): string | undefined => {
2  // failsafe
3  if (!slug) return;
4 
5  const result = slug.replace('-', ' ');
6  return result.charAt(0).toUpperCase() + result.slice(1);
7};
ARRAY
Flatten Multi-Dimensional Array
Makes use of the reduce() function to flatten a multi-dimensional array.
1export const flattenMultiDimensionalArray = (arr: Array<any>) => {
2  return arr.reduce(function (flat, toFlatten) {
3    return flat.concat(
4      Array.isArray(toFlatten)
5        ? flattenMultiDimensionalArray(toFlatten)
6        : toFlatten,
7    );
8  }, []);
9};
ARRAY
Move Array Element Down
Move array element down 1 index position in the array.
1export const moveArrayElementDown = (arr: Array<any>, currentIndex: number) => {
2  if (currentIndex > 0) {
3    let el = arr[currentIndex];
4    arr[currentIndex] = arr[currentIndex - 1];
5    arr[currentIndex - 1] = el;
6  }
7  return [...arr];
8};
ARRAY
Move Array Element Up
Move array element up 1 index position in the array.
1export const moveArrayElementUp = (arr: Array<any>, currentIndex: number) => {
2  if (currentIndex !== -1 && currentIndex < arr.length - 1) {
3    let el = arr[currentIndex];
4    arr[currentIndex] = arr[currentIndex + 1];
5    arr[currentIndex + 1] = el;
6  }
7  return [...arr];
8};
9
NUMBER
Simple Random Number
Basic random number algorithm.
1export const getRandomNumber = (min: number, max: number): number =>
2  Math.floor(Math.random() * (max - min)) + min;
NUMBER
Check if Value is Numeric
Mimics jQuery's isNumeric functionality
1export const isNumeric = (n: any): boolean => {
2  return !isNaN(parseFloat(n)) && isFinite(n);
3};
ARRAY
Get Array of Numbers Within Range
Specify start, end, and step to generate an array of numbers.
1export const getRangeNumbers = (
2  start: number,
3  end?: number,
4  step = 1,
5): Array<number> => {
6  const output = [];
7  if (typeof end === 'undefined') {
8    end = start;
9    start = 0;
10  }
11  for (let i = start; i < end; i += step) {
12    output.push(i);
13  }
14  return output;
15};
STRING
Get Length of String (Text Characters Only)
Using regex, replace any characters that are not valid alphanumeric.
1export const getStrippedDescriptionLength = (
2  rawDescription: string,
3): number => {
4  if (!rawDescription || !rawDescription.length) return 0;
5
6  const strippedDescription = rawDescription.replace(/(<([^>]+)>)/gi, '');
7  return strippedDescription.length;
8};
ARRAY
Get Unique Values From Array

Convert array to a Set to get unique values, then spread back into an array.

1const myArray: Array<any> = ['a', 1, 'a', 2, '1'];
2const unique = [...new Set(myArray)];
ARRAY
Get Matching Number Pairs From Array

Determine the number of matching pairs of values from an array.

1const countMatchingPairs = (ar: Array<number>): number => {
2  const obj = {};
3
4  ar.forEach(item => {
5    obj[item] = obj[item] ? obj[item] + 1 : 1;
6  });
7  
8  return Object.values(obj).reduce((acc, curr) => {
9    acc += Math.floor(curr / 2)
10    return acc;
11  }, 0);
12}
ARRAY
"Count Valleys" Example

As seen on HR, determine the amount of valleys a hiker hiked given an input string.

1const countValleys = (steps: number, path: string): number => {
2    let strArr = path.split('');
3    let count = 0;
4    let result = 0;
5    
6    for(let step=0; step<steps; step++){
7        if(count == 0 && strArr[step].toLowerCase() == 'd'){
8            count -= 1
9            result += 1
10        } else if(strArr[step].toLowerCase() == 'd'){
11            count -= 1
12        } else {
13            count += 1
14        }
15    }
16    return result
17}
ARRAY
"Jumping on Clouds" Example

As seen on HR, determine the minimum amount of jumps needed to avoid the "bad" indexes.

1const jumpingOnClouds = (c: Array<number>) => {
2
3  let current = 0;
4  let jumps = 0;
5  let i = 0;
6
7  // Use a while loop, since it gives more control on adding a dynamic value to a variable.
8  while(i < c.length){                          
9    current = c[i];
10    // Check if 2 clouds ahead from current index is jumpable or not 
11    if(i+2 < c.length && c[i+2] == 0){          
12      // Set the current index to 2 places ahead
13      i+=2;
14      // Make one jump
15      jumps += 1; 
16    // Else Check if next cloud is jumpable or not 
17    } else if(i+1 < c.length && c[i+1] == 0){
18      // Set current index to index of next cloud
19      i+=1;
20      // Again, make one jump
21      jumps += 1;
22    // If none of above if conditions are satisfied, add 1 to index. 
23    } else i+= 1;                               
24  }
25
26  return jumps;
27
28}
ARRAY
"Repeated String" Example

As seen on HR, return the frequency of a character (occurCharacter) within the input string.

1const countCharacterOccurrences = (repeatedString: string, characters: number, occurCharacter: string): number => {
2    const as = repeatedString.split("").filter(stringCharacter => stringCharacter === occurCharacter).length;
3    const times = parseInt(characters / repeatedString.length);
4    const rest = characters % repeatedString.length;
5    
6    const totalAs = times * as
7        + repeatedString.slice(0, rest).split("").filter(c => c === occurCharacter).length
8    
9    return totalAs; 
10}
ARRAY
Circular Rotation Of Array Elements

As seen on HR, rotate array elements left or right, by n rotations.

1const rotateArrayElements = (
2  arr: Array<any>,
3  rotations: number,
4  direction: "left" | "right"
5): Array<any> => {
6  const rotatedArr = [...arr];
7
8  for (let i = 0; i < rotations; i++) {
9    // remove last item and move to front
10    if (direction === "right") {
11      const lastItem = rotatedArr.pop();
12      rotatedArr.unshift(lastItem);
13    } else {
14      // remove front item and move to last
15      const frontItem = rotatedArr.shift();
16      rotatedArr.push(frontItem);
17    }
18  }
19
20  return rotatedArr;
21};
ARRAY
"New Year Chaos" Example

As seen on HR, determine minimum bribes it took for array element to move up positions in the array. If 3 or more bribes, log 'Too chaotic'.

1const minimumBribes = (inputArr: Array<number>) => {
2  let bribesCount = 0;
3  let isTooChaotic = false;
4  for (let i = inputArr.length - 1; i >= 0; i--) {
5    // compare current element with elements in front of it
6    if (inputArr[i] - i > 3) isTooChaotic = true;
7    for (let j = inputArr[i] - 2; j < i; j++) {
8      // for every greater number,
9      if (inputArr[j] > inputArr[i]) bribesCount++;
10    }
11  }
12  if (isTooChaotic) console.log("Too chaotic");
13  else console.log(bribesCount);
14};
ARRAY
"Minimum Swaps 2" Example

As seen on HR, determine minimum amount of swaps required to sort array in ascending order.

1export const minimumSwaps = (arr: Array<number>): number => {
2  let swapCount = 0;
3
4  for (let index = 0; index < arr.length; index++) {
5    const currentInt = arr[index];
6    const position = index + 1;
7    // check if value of current item matches expected position
8    if (currentInt !== position) {
9      let indexToSwap = 0;
10      for (let i = 0; i < arr.length; i++) {
11        if (arr[i] === position) {
12          indexToSwap = i;
13          break;
14        }
15      }
16      arr[indexToSwap] = currentInt;
17      arr[index] = position;
18      swapCount = swapCount + 1;
19    }
20  }
21  return swapCount;
22};
ARRAY
"Array Manipulation" Example

As seen on HR, find the minimum number of swaps required to sort the array in ascending order.

1const arrayManipulation = (
2  arraySize: number,
3  queries: Array<number>
4): number => {
5  // create array with extra elements
6  // to accommodate arr[b + 1] at end
7  // and 1-indexing of queries
8  let arr = Array(arraySize + 2).fill(0);
9  let max = Number.MIN_VALUE;
10  let sum = 0;
11
12  for (let i = 0; i < queries.length; i++) {
13    let [a, b, k] = queries[i];
14
15    // add k to existing value at index
16    arr[a] += k;
17    // subtract to compensate for prefix sum
18    arr[b + 1] -= k;
19  }
20
21  for (let i = 0; i < arr.length; i++) {
22    sum += arr[i];
23    // calculate max as we go
24    max = Math.max(max, sum);
25  }
26
27  return max;
28};
ARRAY
"Bubble Sort" Example

As seen on HR, sort an array of integers using the Bubble Sort algorithm. 

1const countSwaps = (arr: Array<number>) => {
2  let numSwaps = 0;
3
4  for (let i = 0; i < arr.length; i++) {
5    for (let j = 0; j < arr.length - 1; j++) {
6      if (arr[j] > arr[j + 1]) {
7        let temp = arr[j];
8        arr[j] = arr[j + 1];
9        arr[j + 1] = temp;
10        numSwaps += 1;
11      }
12    }
13  }
14
15  console.log("Array is sorted in", numSwaps, "swaps.");
16  console.log("First Element:", arr[0]);
17  console.log("Last Element:", arr[arr.length - 1]);
18};
19
ARRAY
"Mark and Toys" Example

As seen on HR, given a list of prices and amount to spend, determine maximum number of toys that Mark can buy. 

1const maximumToys = (prices: Array<number>, budget: number): number => {
2  let bought = 0;
3  let amountRemaining = budget;
4  const sortedPrices = prices.sort((a, b) => a - b);
5  
6  for (let i = 0; i < sortedPrices.length; i++) {
7      if (amountRemaining < sortedPrices[i]) {
8          break;
9      } else {
10          amountRemaining = amountRemaining - sortedPrices[i];
11          bought++;
12      }
13  }
14  
15  return bought;
16}
ARRAY
"Counting Sort" Example

As seen on HR "Fraudulent Activity Notifications" example, implement a counting sort algorithm to determine the number of notifications the client will receive during a period of n days, given number of trailing days and client's total daily debits.

1const getMedianx2 = (
2  countArr: Array<number>,
3  days: number
4): number | undefined => {
5  let sum = 0;
6
7  for (let i = 0; i < countArr.length; i++) {
8    sum += countArr[i];
9    if (sum * 2 === days) {
10      return i * 2 + 1;
11    }
12    if (sum * 2 > days) {
13      return i * 2;
14    }
15  }
16};
17
18const activityNotifications = (debits: Array<number>, days: number) => {
19  const countArr = new Array(201).fill(0);
20  let notices = 0;
21
22  for (let i = 0; i < days; i++) {
23    countArr[debits[i]]++;
24  }
25
26  for (let i = days; i < debits.length; i++) {
27    const medianx2 = getMedianx2(countArr, days);
28    if (medianx2) {
29      if (debits[i] >= medianx2) notices++;
30      if (i === debits.length - 1) break;
31      countArr[debits[i - days]]--;
32      countArr[debits[i]]++;
33    }
34  }
35
36  return notices;
37};
38
ARRAY
"Making Anagrams" Example

As seen on HR, determine the minimum number of character deletions required to make 2 strings anagrams.

1const makeAnagram = (a: string, b: string): number => {
2  let map: any = {},
3    aCount = 0,
4    bCount = 0;
5  for (let i = 0; i < a.length; i++) {
6    if (!map[a[i]]) {
7      map[a[i]] = 1;
8    } else {
9      map[a[i]] += 1;
10    }
11  }
12
13  for (let j = 0; j < b.length; j++) {
14    if (map[b[j]]) {
15      aCount += 1;
16      map[b[j]] -= 1;
17    } else {
18      bCount += 1;
19    }
20  }
21
22  return a.length - aCount + bCount;
23};