10 JavaScript snippets you can now use

There is no doubt that JavaScript is one of the most popular programming languages in Web development. Whether you use React, Vue or Angular, it's just JavaScript. An extensive and important ecosystem has been developed around JS, providing countless frameworks and libraries to help you develop applications faster.

But sometimes it's best to step back and try to understand how to do things without a library. Take a look at the code snippets below, solve simple problems in an elegant way, and use this knowledge in daily project situations or prepare for coding interviews.

1. Reverse string

In this example, we use the extension operator (...), the reverse method of Array and the join method of String to reverse the given String.

const reverseString = string => [...string].reverse().join('');

// example
reverseString('javascript'); // 'tpircsavaj'
reverseString('good'); // 'doog'

2. Calculate the factorial of the number

To calculate the factorial of a given number, we use arrow functions and nested ternary operators.

const factoriaOfNumber = number => number < 0 ? (() => {
  throw new TypeError('No negative numbers please');
})()
: number <=1 
? 1
: number * factoriaOfNumber(number -1);

// example
factoriaOfNumber(4); // 24
factoriaOfNumber(8); // 40320

3. Convert numbers to an array of numbers

In this example, we use the extension operator (...), the map method of Array and the parseInt function to convert a given number into a singular Array.

const convertToArray = number => [...`${number}`].map(el => parseInt(el));

// example
convertToArray(5678); // [5, 6, 7, 8]
convertToArray(123456789); // [1, 2, 3, 4, 5, 6, 7, 8, 9]

4. Check whether the number is a power of 2

It's simple. We check that the number is not forged AND use the bitwise AND operator (&) to determine whether the number is a power of 2.

const isNumberPowerOfTwo = number => !!number && (number & (number - 1)) == 0;

// example
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 in Object and the map method in Array to map the keys of Object and create an Array of key / value pairs.

const keyValuePairsToArray = object => Object.keys(object).map(el => [el, object[el]]);

// example
keyValuePairsToArray({ Better: 4, Programming: 2 });
// [ ['Better', 4], ['Programming', 2] ]
keyValuePairsToArray({ x: 1, y: 2, z: 3 });
// [ ['x', 1], ['y', 2], ['z', 3] ]

6. Return the [Number] largest elements in the array

To return the largest element from the Array, we use an arrow function that takes the Array and the number of elements we want the function to return. We use the extension operator (...) and the sort and slice methods in Array. Note that if we do not provide the second parameter, the default value of number is 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]); // [5]
maxElementsFromArray([7,8,9,10,10],2); // [10, 10]

7. Check whether all elements in the array are equal

In this short example, we use the every method in Array to check whether all elements in the Array are equal. We basically check whether each element is equal to the first element in the Array.

const elementsAreEqual = array => array.every(el => el === array[0]);

// example
elementsAreEqual([9,8,7,6,5]); // false
elementsAreEqual([4,4,4,4,4]); // true

8. Return the average of two numbers

In this example, we use the extension operator (...) and the reduce method in Array to return the average of two given numbers or an Array.

const averageOfTwoNumbers = (...numbers) => numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0) / numbers.length;

// example
averageOfTwoNumbers(...[6,7,8]); // 7
averageOfTwoNumbers(6,7,8,9); // 7.5

9. Returns the sum of two or more numbers

To return the sum of two or more given numbers or an Array, we use the extension operator (...) and the reduce method in Array again.

const sumOfNumbers = (...array) => [...array].reduce((accumulator, currentValue) => accumulator + currentValue, 0);

// example
sumOfNumbers(5,6,7,8,9.10); // 45
sumOfNumbers(...[1,2,3,4,5,6,7,8,9,10]); // 50

10. Return the power set of the number array

In the last example, we want to return the power set of the number Array. Therefore, we use the reduce, map and concat methods in Array.

const powersetOfArray = array => array.reduce((accumulator, currentValue) => accumulator.concat(accumulator.map(el => [currentValue].concat(el))), [[]]);

// example
powersetOfArray([4, 2]); // [[], [4], [2], [2, 4]]
powersetOfArray([1, 2, 3]); /
// [[], [1], [2], [2, 1], [3], [3, 1], [3, 2], [3, 2, 1]]

As you can see, using JavaScript and some ES6 magic to solve these tasks is not always difficult.

Tags: Javascript array function reduce

Posted by Boerboel649 on Wed, 25 May 2022 21:22:40 +0300