Today we share some single-line code skills. Understanding these skills can improve our work efficiency. Now, let’s take a look at these single-line code skills today.
array
1. Check if the variable is an array
const isArray = Array.isArray(arr);
const isArray = arr instanceof Array;
2. Sum of numeric arrays
const sum = (arr) => arr.reduce((a, b) => a + b);
3. Remove Falsy values from array
const removeFalsyValues = (arr) => arr.filter(x => x);
// or
const removeFalsyValues = (arr) => arr.filter(Boolean);
4. Average of numeric arrays
const average = (arr) => arr.reduce((a, b) => a + b) / arr.length;
5. Merge and remove duplicates
const merge = (arr1, arr2) => [...new Set(arr1.concat(arr2))];
// or
const merge = (arr1, arr2) => [...new Set([...arr1, ...arr2])];
6. Merge two arrays
const merge = (arr1, arr2) => [].concat(arr1, arr2);
// or
const merge = (arr1, arr2) => [...arr1, ...arr2];
7. Shuffle the array
const shuffle = (arr) => arr.slice().sort(() => Math.random() - 0.5);
8. Get the last element of the array
const lastElement = (arr) => arr[arr.length-1];
// or
const lastElement = (arr) => arr.slice(-1)[0];
// or
const lastElement = (arr) => arr.slice().pop();
9. Find unique values in an array
const findUniqueValues = (arr) => arr.filter((i) => arr.indexOf(i) === arr.lastIndexOf(i));
10. Clone array
const clone = (arr) => arr.slice();
// or
const clone = (arr) => [...arr];
string
11. Capitalize strings
const capitalize = (str) => str.charAt(0).toUpperCase() + str.slice(1);
12. String reversal
const reverseString = (str) => str.split("").reverse().join("");
// or
const reverseString = (str) => [...str].reverse().join();
13. Convert string to number
const toNumber = (str) => Number(str);
// or
const toNumber = (str) => +str;
14. Convert string to character array
const toCharArray = (str) => str.split('');
// or
const toCharArray = (str) => [...str];
// or
const toCharArray = (str) => Array.from(str);
// or
const toCharArray = (str) => Object.assign([], str);
15. Convert Snake case to Camel case
const snakeToCamel = (str) => str.toLowerCase().replace(/(_\w)/g, (word) => word.toUpperCase().substr(1));
date
16. Number of days between two dates
const daysBetweenDates = (date1, date2) => Math.ceil(Math.abs(date1 - date2) / (1000 * 60 * 60 * 24));
17. Weekday appointments
const getWeekday = (date) => ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'][date.getDay()];
// or
const getWeekday = (date) => date.toLocaleString('en-US', {weekday: 'long'});
random
18. Random number generator
const randomNumber = (rangeStart, rangeEnd) => new Date().getTime() % rangeEnd + rangeStart;
// or
const randomNumber = (min, max) => Math.floor(Math.random() * (max - min + 1) + min);
19. Random Hex Color Generator
const randomHexColor = () => `#${Math.random().toString(16).slice(2, 8).padEnd(6, '0')}`;
20. Random Boolean Generator
const randomBoolean = () => Math.random() >= 0.5;
verify
21. Check if array is empty
const isEmpty = (arr) => !Array.isArray(arr) || !arr.length;
22. Check if array contains value
const includes = (arr, value) => arr.indexOf(value) != -1;
// or
const includes = (arr, value) => arr.includes(value);
23. Check if date is on weekend
const isWeekend = (date) => [5, 6].indexOf(date.getDay()) !== -1;
Network Utilities
24. Copy to clipboard
const copyToClipboard = (text) =>
navigator.clipboard?.writeText && navigator.clipboard.writeText(text);
// Testing
copyToClipboard("Hello World!");
25. Detect Dark Mode
const isDarkMode = () =>
window.matchMedia &&
window.matchMedia("(prefers-color-scheme: dark)").matches;
// Testing
console.log(isDarkMode());
Summarize
The above content is all I want to share with you today. I hope this content can be helpful to you.
For more exciting tutorials, please search "Qianfeng Education" on Station B
Qianfeng front-end teacher Xixiya’s HTML+CSS tutorial, a must-see video for getting started with zero-based web front-end development