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.
1. Reverse a String
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
2. Calculate a Number's Factorial
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
3. Convert a Number to an Array of Digits
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]
4. Check If a Number Is a Power of Two
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
5. Create an Array of Key-Value pairs From an Object
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] ]
6. Return [Number] Maximum Elements from an Array
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]
7. Check if All Elements in an Array Are Equal
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
8. Return the Average of Two Numbers
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
9. Return the Sum of Two or More Numbers
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
10. Return the PowerSet of an Array Of Numbers
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.
Top comments (0)