26

TNTWeb-the full name of Tencent News China Taiwan front-end team, the small partners in the group have practice and accumulation in the front-end web, NodeJS development, UI design, mobile APP and other big front-end fields.

At present, the team mainly supports the front-end development of Tencent News's various businesses. In addition to business development, it has also accumulated some front-end infrastructure to empower business efficiency and product innovation.

The team advocates open source and co-construction, and has a variety of technical experts. The team GitHub address: https://github.com/tnfe

The author of this article Summoner cz GitHub: https://github.com/xucz

When developing a JavaScript project, we often use some tool functions that have been developed before. Collect these functions. When you need them, it will save you a lot of development time. This article will bring you 15 commonly used tool functions. , You can use them to solve problems in an elegant way.
  1. Reversal number
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
  1. Get the largest n numbers 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]
  1. Calculate the factorial
const factorial = (number) =>
  number < 0
    ? (() => {
      throw new TypeError('类型错误');
    })()
    : number <= 1
    ? 1
    : number * factorial(number - 1);

factorial(4); // 24
factorial(10); // 3628800
  1. Determine whether the current operating environment is a browser
const isBrowser = () => ![typeof window, typeof document].includes('undefined');

isBrowser(); // false (Node)
isBrowser(); // true (browser)
  1. Determine whether the current operating environment is Node.js
const isNode = () =>
  typeof process !== 'undefined' &&
  !!process.versions &&
  !!process.versions.node;

isNode(); // true (Node)
isNode(); // false (browser)
  1. Get 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'}
  1. rgb(x,x,x) color expression format 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}

  1. Escape the string for use in HTML
const escapeHTML = str =>
  str.replace(
    /[&<>'"]/g,
    tag =>
      ({
        '&': '&amp;',
        '<': '&lt;',
        '>': '&gt;',
        "'": '&#39;',
        '"': '&quot;'
      }[tag] || tag)
  );

escapeHTML('<a href="#">tntweb</a>'); 
  1. Unescapes escapes HTML characters
const unescapeHTML = str =>
  str.replace(
    /&amp;|&lt;|&gt;|&#39;|&quot;/g,
    tag =>
      ({
        '&amp;': '&',
        '&lt;': '<',
        '&gt;': '>',
        '&#39;': "'",
        '&quot;': '"'
      }[tag] || tag)
  );

unescapeHTML('&lt;a href=&quot;#&quot;&gt;tntweb&lt;/a&gt;');
  1. Generate random integers in the specified range
const randomIntegerInRange = (min, max) =>
  Math.floor(Math.random() * (max - min + 1)) + min;

randomIntegerInRange(1, 7); // 1 - 7
  1. Convert tilde path to absolute path
const reversePath = str =>
  str.replace(/^~($|\/|\\)/, `${require('os').homedir()}$1`);

reversePath('~/web'); // '/Users/[userName]/web'
  1. Get the current URL without any parameters or fragment identifier
const getBaseURL = url => url.replace(/[?#].*$/, '');

getBaseURL('https://xx.com/index?name=tntweb&company=tencent');
// https://xx.com/index
  1. Returns the length of the string in bytes
const byteSize = str => new Blob([str]).size;

byteSize('🚗'); // 4
byteSize('Hello World'); // 11
  1. Randomly get the elements in the array
const randomly = arr => arr[Math.floor(Math.random() * arr.length)];

randomly([1, 3, 5, 7, 9, 11]);
  1. Check if 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

Recommended items

ffcreator

FFCreator is a lightweight and flexible short video processing library node.js You only need to add a few pictures or video clips and a background music, you can quickly generate a cool video clip.


TNTWEB
3.8k 声望8.5k 粉丝

腾讯新闻前端团队