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