17
10 Daily useful JS code snippets
JavaScript is without question one of the most popular programming languages in web dvelopment.
Take a look at following code snippets that solve similar problems in an elegant way and use this knowledge in daily project situations or to prepare for any upcoming coding interviews.
In this example, we are using the spread operator (...), the reverse method from Array, and the join method from String to reverse a given string.
const reverseString = string => [...string].reverse().join('');
//Examples
reverseString('devto'); //otved
reverseString('AdityaSharan'); //narahSaytidA
To calculate the factorial of a given number, we can make use of arrow function and nested ternary operators.
const factorialOfNumber= number =>
number < 0 ?
( () =>
{
throw new TypeError('No negative numbers please');
}
)()
: number <= 1
? 1
:number * factorialOfNumber(number -1);
//Examples
factorialOfNumber(4); //24
factorialOfNumber(8); //40320
In this example,we use spread operator (...),the map method of Array and the parseInt function to convert a given number to an array of single digits.
const convertToArrays = number => [...`${number}`].map(ele =>
parseInt(ele));
//Examples
convertToArrays(5678); //[5,6,7,8]
convertToArrays(123456789); //[1,2,3,4,5,6,7,8,9]
This one is pretty Straight forward.We check that number is not falsy and use the bitwise AND operator (&) to determine if number is power of two.
const isNumberPowerOfTwo = number => !!number && (number & (
number -1)) == 0 ;
//Examples
isNumberPowerOfTwo(100); //false
isNumberPowerOfTwo(128); //true
In this example, we use the keys method from Object and the map method from Array to map over Object's keys and create an array of key-value pairs.
const keyValuePairsToArray = object => Object.keys(object)
.map(ele => [ele,object[el]]);
//Examples
keyValuePairsToArray({Java :4 ,Script : 2});
// [ ['Java', 4] , ['Script',2] ]
keyValuePairsToArray( {x:1, y:5, z:8} );
// [ ['x',1], ['y',5], ['z',3] ]
To return the maximum elements from an array, we use an arrow function that takes our array and the number of elements we want the function to return. We use the spread operator(...) and the sort and slice methods from Array. Note that if we dont provide a second argument,number gets a default value of 1, so only one maximum element is returned.
const maxElementsFromArray = (array,number =1) =>[...array]
.sort((x,y) => y-x).slice(0,number);
//Example
maxElementsFromArray([1,2,3,4,5,6,7]); //[7]
In this example,we check if all elements in an array by using the every method from Array. We basically chekc if every element is equal to the first element in the array.
const elementsAreEqual = array => array.every( ele => ele=== array[0]);
//Examples
elementsAreEqual([9,8,7,6,5,4]); // false
elementsAreEqual([2,2,2,2,2,2,2]); // true
In this example,we use the spread operator(...) and the reduce method from Array to return the average of two given numbers or an array.
const averageOfTwoNumbers = (...numbers) => numbers.reduce((accumulator, currentValue) => accumulator+currentValue,0) /numbers.length
//Examples
averageOfTwoNumbers (...[6,7,8]); // 7
To return the sum of two or more given numbers or an array, we agauin use the spread operator (...) and the reduce method from an Array.
const sumOfNumbers = (...array) => [...array].reduce((accumulator,currentValue) => accumulator + currentValue, 0);
//Examples
sumOfNumbers(5,6,7,8,9,10); //45
In the last Example,we want to return the powerset of an array of numbers.Therefore we use the reduce,map and the concat methods from Array.
const powersetOfArray = array => array.reduce((accumulator,currentValue) => accumulator.concat(accumulator.map(ele => [currentValue].concat(el))),[ [] ] );
//ExAMPLES
powersetOfArray([4,2]);
// [[],[4],[2],[2,4]]
As you can see it isn't always difficult to solve these tasks with Javascript and some ES6 Magic.
Thanks for reading!
Don't forget to like this post and
Do let me knw if you knw some good code snippets that can be added in the list so that even I can learn from it.
17