Useful code snippets for use in your next web application. Everything from Typescript, useful array methods, API paginating functions, SCSS, etc.
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};
1const isPalindrome = (inputString: string): boolean => {
2 const revString = inputString.split('').reverse().join('');
3 return revString === str;
4};
1const isAnagram = (aString: string, bString: string): boolean => {
2 return aString.split('').sort().join('') === bString.split('').sort().join('');
3};
1const flattenArray = (inputArrays: Array<any>): Array<any> => {
2 return inputArrays.reduce((arrayA: Array<any>, arrayB: Array<any>) => {
3 return arrayA.concat(arrayB);
4 });
5};
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};
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};
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};
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};
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};
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}
1const seekAndDestroy = (
2 inputArr: Array<any>,
3 removeArr: Array<any>
4): Array<any> => {
5 return inputArr.filter((item: any) => !removeArr.includes(item));
6};
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};
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};
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});
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};
1export const formatDate = (rawDate: string, localeString = 'en-US'): string => {
2 return new Date(rawDate).toLocaleDateString(localeString);
3};
1export const getPageIndexesArray = (totalPages: number): Array<number> => {
2 return totalPages > 1 ? Array.from(Array(totalPages).keys()) : [0];
3};
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};
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};
1export const removeQuotes = (input: string): string => {
2 return input.replace(/['"]+/g, '');
3};
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};
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};
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};
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};
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
1export const getRandomNumber = (min: number, max: number): number =>
2 Math.floor(Math.random() * (max - min)) + min;
1export const isNumeric = (n: any): boolean => {
2 return !isNaN(parseFloat(n)) && isFinite(n);
3};
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};
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};