Top Javascript snippets

javascript snippet example

Shuffle an Array

const shuffleArray = (arr) => arr.sort(() => 0.5 - Math.random());
console.log(shuffleArray([1, 2, 3, 4]));
// Result: [ 1, 4, 3, 2 ]
  • The code shuffles an array of numbers.
  • The code uses a function called sort that takes two parameters: the first parameter is the function to be used for sorting, and the second parameter is a callback function that will be executed after each item in the array has been sorted.
  • This callback function returns 0.5 – Math.random() which will return values between 0 and 1 with equal probability.
  • The code is a function that takes an array and returns a new array with the values shuffled.

Check if Date is Valid

const isDateValid = (...val) => !Number.isNaN(new Date(...val).valueOf());
isDateValid("December 17, 1995 03:24:00");
// Result: true

 

  • The code is checking if the value of a new Date object is NaN.
  • If it is, then the function returns true.
  • The code will return true if the value of the parameter is a valid date.

 

Copy to Clipboard

const copyToClipboard = (text) => navigator.clipboard.writeText(text);
copyToClipboard("Hello World");
  • The code copies the text “Hello World” to the clipboard.

Find the day of the year

const dayOfYear = (date) =>
  Math.floor((date - new Date(date.getFullYear(), 0, 0)) / 1000 / 60 / 60 / 24);
dayOfYear(new Date());
// Result: 272

 

  • The code calculates the day of year for a given date.
  • The code starts by calculating the number of days in a year, which is 365.25 days.
  • Then it divides that number by 1000 to get the remainder and then multiplies that remainder by 60 to get minutes, multiplying it again by 60 to get seconds, and finally dividing it by 24 hours to get hours.
  • The first line calculates how many days there are in a year: 365.25 The second line calculates what’s left over after dividing this number into 1000: 0 The third line multiplies this value with 60 (minutes) The fourth line multiplies this value with another 60 (seconds) And finally divides this value into 24 hours: 0
  • The code will calculate the day of year for a given date.

Capitalize a String

const capitalize = str => str.charAt(0).toUpperCase() + str.slice(1)
capitalize("follow for more")
// Result: Follow for more
  • The code is trying to capitalize the first letter of each word in a string.
  • The code starts by using str => str.charAt(0).toUpperCase() + str.slice(1) to get the first character of each word, then it uses that value as an index into the string and capitalizes it with .toUpperCase().
  • The code is a method of converting a string to uppercase.

Find the number of days between two days

const dayDif = (date1, date2) => Math.ceil(Math.abs(date1.getTime() - date2.getTime()) / 86400000)
dayDif(new Date("2020-10-21"), new Date("2021-10-22"))
// Result: 366
  • The code calculates the difference in days between two dates.
  • The code calculates the dayDif by taking the absolute value of the difference in time and dividing it by 86400000 (the number of seconds in a day).
  • The result is 366, which means that there are 365 days from 2020-10-21 to 2021-10-22.
  • The code calculates the difference in days between two dates, and returns 366.

Clear All Cookies

const clearCookies = document.cookie.split(';').forEach(cookie => document.cookie = cookie.replace(/^ +/, '').replace(/=.*/, =;expires=${new Date(0).toUTCString()};path=/));

Here‘s what the above function is doing:

1. It‘s getting thedocument object. This is the DOM element of the current page.

2. It‘s retrieving the document‘s cookies. These are the cookies the page is storing.

3. It loops through the cookies, removing the semicolon and the equal sign (=) from each cookie.

4. It sets the document‘s cookie to the modified version.

5. The clearCookies() function is executed after each page load. Now that we have aclean document, we can begin the process of converting it to HTML. The first step is to get the HTML code from the text string. This can be accomplished using theinnerHTML property of the document object.

Generate Random Hex

const randomHex = () => #${Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, "0")};
console.log(randomHex());
// Result: #92b008
  •  The code is a function that returns a random hexadecimal number. – The code is written in JavaScript, and the function uses Math.random() to generate a random number between 0x0 and 0xffffff (16 bits). – The result of this calculation is then converted into an integer by using the string “0” as padding at the end of each six-digit hexadecimal value.
  •  The code generates a random hexadecimal string.

Remove Duplicated from Array

const removeDuplicates = (arr) => [...new Set(arr)];
console.log(removeDuplicates([1, 2, 3, 3, 4, 4, 5, 5, 6]));
// Result: [ 1, 2, 3, 4, 5, 6 ]
  • The code is a function that takes an array as input and returns the same array with all duplicates removed.
  •  The code will remove all the duplicates from an array.

Get Query Params from URL

const getParameters = (URL) => {
  URL = JSON.parse('{"' + decodeURI(URL.split("?")[1]).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g, '":"') +'"}');
  return JSON.stringify(URL);
};
getParameters(window.location)
// Result: { search : "easy", page : 3 }
  • The code gets the parameters from the URL, which is a string. – It then parses out the search and page numbers from that string. – The code then returns those values as JSON to be parsed by another function.
  •  The code is meant to get the parameters of a URL.

Log Time from Date

const timeFromDate = date => date.toTimeString().slice(0, 8);
console.log(timeFromDate(new Date(2021, 0, 10, 17, 30, 0))); 
// Result: "17:30:00"
  • The code is trying to convert a date object into a time string.
  • The code starts by using the function timeFromDate which takes in an argument of type Date and returns a string with hours, minutes, seconds, and milliseconds.
  • Then it uses the slice method on that returned value to remove the first 8 characters from the result.
  • The program then logs out what was left over after removing those 8 characters: “17:30”.
  • The code will output “17:30:00”

Find Average of Numbers

const average = (...args) => args.reduce((a, b) => a + b) / args.length;
average(1, 2, 3, 4);
// Result: 2.5
  • The code calculates the average of an array of numbers.

Check if the array is empty

const isNotEmpty = arr => Array.isArray(arr) && arr.length > 0;
isNotEmpty([1, 2, 3]);
// Result: true
  • The code checks if the array is empty or not.

Get Selected Text

const getSelectedText = () => window.getSelection().toString();
getSelectedText();
  • The code gets the selected text in the browser.

Detect Dark Mode

const isDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches
console.log(isDarkMode) // Result: True or False
  • The code is checking if the browser supports dark mode. – If it does, then it sets a variable called isDarkMode to true.
  •  The code checks if the current browser window is in dark mode. – If it is, then true will be returned.

Leave a Comment