Javascript short reusable functions everyone will always need

Rahul Sharma (DevsMitra)
3 min readMar 11, 2022

--

Javascript short reusable functions everyone will always need | Rahul Sharma(DevsMitra)
Javascript short reusable functions everyone will always need

Most of you probably already know them. lodash/underscore was built to provide utility functions for common tasks in Javascript. But some you don’t want to install a package for the small use case.

This blog will help you to save some time and effort to create utility functions.

Create an array of numbers from 1 to n

const range = (n) => Array.from({ length: n }, (_, i) => i + 1);
console.log(range(10));

Shuffling an array

const shuffle = (arr) => arr.sort(() => 0.5 - Math.random());
console.log(shuffle([1, 2, 3, 4]));
// Result: [3, 2, 1, 4]

Remove Duplicated from Array

const removeDuplicated = (arr) => [...new Set(arr)];
console.log(removeDuplicated([1, 2, 3, 3, 4, 4, 5, 5, 6]));
// Result: [ 1, 2, 3, 4, 5, 6 ]

The number is even or not

const isEven = (num) => (num % 2 === 0);
console.log(isEven(4));
// Result: true

Find the sum of an array

const sum = (arr) => arr.reduce((a, b) => a + b, 0);
console.log(sum([1, 2, 3, 4]));
// Result: 10

Find largest numbers

const findLargest = (arr) => arr.map(subArr => Math.max(...subArr));
console.log(findLargest([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]));
// Result: [5, 27, 39, 1001]

Find the range of an array

const range = (arr) => Math.max(...arr) - Math.min(...arr);
console.log(range([1, 2, 3, 4]));
// Result: 3

Reverse String

const reverseString = (str) => str.split('').reverse().join('');
console.log(reverseString('hello'));
// Result: olleh

Generate Title Case

const titleCase = (str) => str.split(' ').map(word => word[0].toUpperCase() + word.slice(1).toLowerCase()).join(' ');
console.log(titleCase('the quick brown fox'));
// Result: The Quick Brown Fox

String Palindrome

const isPalindrome = (str) => s === s.split('').reverse().join('');
console.log(isPalindrome('madam'));
// Result: true

Copy to Clipboard

const copyToClipboard = (t) => navigator.clipboard.writeText(t);
copyToClipboard("Hello World");

Find the day of the week

const getDayName = (date) => {
const days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday','Thursday', 'Friday', 'Saturday'];
return days[date.getDay()];
};
console.log(getDayName(new Date()));
// Result: Friday

Find the day of the year

const getDayOfYear = (date) => {
const firstDay = new Date(date.getFullYear(), 0, 1);
return Math.ceil((date - firstDay) / 86400000);
};
console.log(getDayOfYear(new Date()));
// Result: 182

Find the number of seconds until midnight

const getSecondsUntilMidnight = (date) => (24 - date.getHours()) * 60 * 60 + (60 - date.getMinutes()) * 60 + (60 - date.getSeconds());
console.log(getSecondsUntilMidnight(new Date()));
// Result: 86400

Generate a random color

const getRandomColor = () => `#${Math.floor(Math.random() * 16777215).toString(16)}`;
console.log(getRandomColor());
// Result: #f0f0f0

Get selected text

const getSelectedText = () => window.getSelection().toString();
console.log(getSelectedText());
// Result: Hello World

Time the execution of your code

console.time('time');
for (let i = 0; i < 1000000; i++) { // do something }
console.timeEnd('time'); // time: 0.827ms

Map an array without using .map()

const map = (arr, cb) => Array.from(arr, cb);
console.log(map([1, 2, 3, 4], n => n * 2)); // [2, 4, 6, 8]

Find the intersection of two arrays

const intersection = (arr1, arr2) => {
const set = new Set(arr1);
return arr2.filter((x) => set.has(x));
};
console.log(intersection([1, 2, 3], [2, 3, 4])); // [2, 3]

Remove falsy values from an array

const compact = (arr) => arr.filter(Boolean);
console.log(
compact([0, 1, false, 2, '', 3, 'a', 'e' * 23, NaN, 's', 34])
); // [1, 2, 3, 'a', 's', 34]

I’ve created a public repository for other utility functions also feel free to contribute to the project.

Demo: https://devsmitra.github.io/javascript-quick-functions

Repo: https://github.com/devsmitra/javascript-quick-functions

Got any questions or additional? please leave a comment.

Thank you for reading 😊

--

--

Rahul Sharma (DevsMitra)
Rahul Sharma (DevsMitra)

Written by Rahul Sharma (DevsMitra)

I’m a technology enthusiast who does web development. Passionate to contribute to open-source projects and make cool products.

No responses yet