18 useful JavaScript fragments
Original address: medium.com/javascript-… Written by Amy J. Andrews
If someone asked me what programming language to learn as a beginner, I would recommend JavaScript, a powerful language that touches almost every aspect of programming – front end, back end, Web applications, desktop applications, mobile applications, and so on.
In this article I’ll show you 18 commonly used JavaScript fragments that have saved me a lot of time in my daily development work.
1. maxItemOfArray
Gets the largest number in the array
const maxItemOfArray = (arr) = > arr.sort((a, b) = > b - a)[0];
let maxItem = maxItemOfArray([3.5.12.5]);
Copy the code
2. areAllEqual
Check that all items in the array are equal
const areAllEqual = array= > array.every(item= > item === array[0]);
let check1 = areAllEqual([3.5.2]); // false
let check2 = allEqual([3.3.3]); // true
Copy the code
3. averageOf
Take the average of a given number
const averageOf = (... numbers) = > numbers.reduce((a, b) = > a + b, 0) / numbers.length;
let average = averageOf(5.2.4.7); / / 4.5
Copy the code
4. reverseString
Invert a string
const reverseString = str= >STR [...]. Reverse (). The join (");letA = reverseString(' Have a nice day! ');/ /! yad ecin a evaH
Copy the code
5. sumOf
Find the sum of the given numbers
Const sumOf = (... numbers) => numbers.reduce((a, b) => a + b, 0); let sum = sumOf(5, -3, 2, 1); / / 5Copy the code
6. findAndReplace
Looks for the given word in the string and replaces it with another word
const findAndReplace = (string, wordToFind, wordToReplace) = > string.split(wordToFind).join(wordToReplace);
letResult = findAndReplace(' I like banana ', 'banana', 'apple');// I like apple
Copy the code
7. RGBToHex
Convert RGB colors to hexadecimal
const RGBToHex = (r, g, b) = > ((r << 16) + (g << 8) + b).toString(16).padStart(6, '0');let hex = RGBToHex(255.255.255); // ffffff
Copy the code
8. shuffle
How does a music player randomly play a play item?
const shuffle = (Array [...]) = > {
let m = array.length;
while (m) {
const i = Math.floor(Math.random() * m -); [array[m], array[i]] = [array[i], array[m]]; }return array;
};
shuffle([5.4.3.6.20]);
Copy the code
9. removeFalseValues
Delete false values from the array, including false, undefined, NaN, and empty
const removeFalseValues = arr= > arr.filter(item= > item);
let arr = removeFalseValues([3.4.false, ' ',5.true.undefined.NaN, ' ']);// [3, 4, 5, true]
Copy the code
10. removeDuplicatedValues
Removes duplicate items from the array
const removeDuplicatedValues = array= >[...new Set(array)];
let arr = removeDuplicatedValues([5.3.2.5.6.1.1.6]); // [5, 3, 2, 6, 1]
Copy the code
11. getTimeFromDate
Returns the time as a string of date objects
const getTimeFromDate = date= > date.toTimeString().slice(0.8);
let time = getTimeFromDate(new Date()); / / 09:46:08
Copy the code
12. capitalizeAllWords
Capitalize the first letter of all words in the string
const capitalizeAllWords = str= > str.replace(/\b[a-z]/g.char= > char.toUpperCase());
letSTR = capitalizeAllWords(' I love reading book ');// I Love Reading Book
Copy the code
13. getDayDiff
Returns the difference in days between two dates
const getDayDiff = (date1, date2) = > ((date2 - date1) / (1000 * 3600 * 24));
let diff = getDayDiff(new Date('2020-04-01'), new Date('2020-08-15')); / / 136
Copy the code
14. radianToDegree
Convert radians to degrees
const radianToDegree = radian= > (radian * 180.0) / Math.PI;
let degree = radianToDegree(2.3); / / 131.78
Copy the code
15. isValidJSON
Checks if the given string is valid JSON
const isValidJSON = string= > {
try {
JSON.parse(string);
return true;
} catch (error) {
return false; }};letCheck1 = isValidJSON(' {" title ":" javascript ", "price" :14} ');// true
letCheck2 = isValidJSON(' {" title ":" javascript ", "price" :14, the subtitle} ');// false
Copy the code
16. toWords
Converts the given string to an array of words
const toWords = (string, pattern = /[^a-zA-Z-]+/) = > string.split(pattern).filter(item= > item);
letWords = toWords(' I want to be come a great programmer ');/ / / "I", "want", "to", "be" and "has", "a", "great", "programmer"]
Copy the code
17. scrollToTop
Is at the bottom of a long page and wants to scroll up quickly to the top
const scrollToTop = () = > {
const t = document.documentElement.scrollTop || document.body.scrollTop;
if (t > 0) {
window.requestAnimationFrame(scrollToTop);
window.scrollTo(0, t -- t /8); }};Copy the code
18. isValidNumber
Verify that the number is valid
const isValidNumber = n= > !isNaN(parseFloat(n)) && isFinite(n) && Number(n) === n;
let check1 = isValidNumber(10); // true
letCheck2 = isValidNumber (' a ');// false
Copy the code
If you have a useful snippet of your own, let me know in the comments below.