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};