TNTWeb – The full name of Tencent News Zhongtai front-end team, partners in the group have practiced and accumulated experience in Web front-end, NodeJS development, UI design, mobile APP and other large front-end fields.
At present, the team mainly supports the front-end development of Tencent news business. Besides business development, some front-end infrastructure has been accumulated to enable business efficiency improvement and product innovation.
The team advocates open source construction, has a variety of technical masters, the team GitHub address: github.com/tnfe
The author of this article is CZ GitHub: github.com/xucz
When developing a JavaScript project, it’s common to use previously developed utility functions. Collecting these functions will save you a lot of development time when you need them. This article brings you 15 common utility functions that you can use to solve problems in an elegant way.
- Reverse digital
const reverseNumber = n= >
parseFloat(`${n}`.split(' ').reverse().join(' ')) * Math.sign(n);
reverseNumber(123); / / 321
reverseNumber(-200); / / - 2
reverseNumber(32.4); / / 4.23
reverseNumber(-32.4); // -4.23
Copy the code
- Gets the largest n number in the array
const maxFromArray = (array, number = 1) = > [...array]
.sort((x, y) = > y -x).slice(0, number);
maxFromArray([2.1.4.3.5.6]); / / [6]
maxFromArray([2.1.4.3.6.6].2); / / [6, 6]
Copy the code
- Calculating factorial
const factorial = (number) = >
number < 0
? (() = > {
throw new TypeError('Type error');
})()
: number <= 1
? 1
: number * factorial(number - 1);
factorial(4); / / 24
factorial(10); / / 3628800
Copy the code
- Check whether the current operating environment is a browser
const isBrowser = () = >! [typeof window.typeof document].includes('undefined');
isBrowser(); // false (Node)
isBrowser(); // true (browser)
Copy the code
- Check whether the current running environment is Node.js
const isNode = () = >
typeofprocess ! = ='undefined'&&!!!!! process.versions && !! process.versions.node; isNode();// true (Node)
isNode(); // false (browser)
Copy the code
- Gets the parameters on the URL
const getURLParams = url= >
(url.match(/([^?=&]+)(=([^&]*))/g) || []).reduce(
(a, v) = > (
(a[v.slice(0, v.indexOf('='))] = v.slice(v.indexOf('=') + 1)), a
),
{}
);
getURLParams('qq.com'); / / {}
getURLParams('https://xx.com?name=tntweb&age=20');
// {name: 'tntweb', age: '20'}
Copy the code
rgb(x,x,x)
Color representation format is converted to object format
const toRGBObject = rgbStr= > {
const [red, green, blue] = rgbStr.match(/\d+/g).map(Number);
return { red, green, blue };
};
toRGBObject('rgb(100, 150, 200)'); // {red: 100, green: 150, blue: 200}
Copy the code
- Escape strings for use in HTML
const escapeHTML = str= >
str.replace(
/[&<>'"]/g.tag= >
({
'&': '& '.'<': '< '.'>': '> '."'": '& # 39; '.'"': '" '
}[tag] || tag)
);
escapeHTML('<a href="#">tntweb</a>');
Copy the code
- Unescapes HTML characters
const unescapeHTML = str= >
str.replace(
/& |< |> | & # 39; |" /g.tag= >
({
'& ': '&'.'< ': '<'.'> ': '>'.'& # 39; ': "'".'" ': '"'
}[tag] || tag)
);
unescapeHTML('< a href=" #" > tntweb< /a> ');
Copy the code
- Generates a random integer in the specified range
const randomIntegerInRange = (min, max) = >
Math.floor(Math.random() * (max - min + 1)) + min;
randomIntegerInRange(1.7); / / 1-7
Copy the code
- Convert the tilde path to an absolute path
const reversePath = str= >
str.replace(($| / / ^ ~| \) /,`The ${require('os').homedir()}$1 `);
reversePath('~/web'); // '/Users/[userName]/web'
Copy the code
- Gets the current URL without any parameters or fragment identifiers
const getBaseURL = url= > url.replace(/ [? #]. * $/.' ');
getBaseURL('https://xx.com/index?name=tntweb&company=tencent');
// https://xx.com/index
Copy the code
- Returns the length of the string in bytes
const byteSize = str= > new Blob([str]).size;
byteSize('🚗'); / / 4
byteSize('Hello World'); / / 11
Copy the code
- Gets the elements of the array randomly
const randomly = arr= > arr[Math.floor(Math.random() * arr.length)];
randomly([1.3.5.7.9.11]);
Copy the code
- Check that the string is valid JSON
const isValidJSON = str= > {
try {
JSON.parse(str);
return true;
} catch (e) {
return false; }}; isValidJSON('{"name":"tntweb","age":20}'); // true
isValidJSON('{"name":"tntweb",age:"20"}'); // false
isValidJSON(null); // true
Copy the code