15 JavaScript functions worth collecting

15 JavaScript functions worth collecting

1. Reverse the numbers

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

2. 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]


3. Calculate factorial

const factorial = (number) =>
  number < 0
    ? (() => {
      throw new TypeError('Type error');
    })()
    : number <= 1
    ? 1
    : number * factorial(number - 1);

factorial(4); // 24
factorial(10); // 3628800


4. Determine whether the current operating environment is a browser

const isBrowser = () => ![typeof window, typeof document].includes('undefined');

isBrowser(); // false (Node)
isBrowser(); // true (browser)


5. 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)


6. 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'}


7. Convert rgb(x,x,x) color expression format 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}

8. Escape strings for use in HTML

const escapeHTML = str =>
  str.replace(
    /[&<>'"]/g,
    tag =>
      ({
        '&': '&amp;',
        '<': '&lt;',
        '>': '&gt;',
        "'": '&#39;',
        '"': '&quot;'
      }[tag] || tag)
  );

escapeHTML('<a href="#" rel="external nofollow" >tntweb</a>'); 


9. Unescapes escape 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;');


10. Generate a random integer within a specified range

const randomIntegerInRange = (min, max) =>
  Math.floor(Math.random() * (max - min + 1)) + min;

randomIntegerInRange(1, 7); // 1 - 7


11. Convert the tilde path to an absolute path

const reversePath = str =>
  str.replace(/^~($|\/|\\)/, `${require('os').homedir()}$1`);

reversePath('~/web'); // '/Users/[userName]/web'


12. Get 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


13. Return the length of the string in bytes

const byteSize = str => new Blob([str]).size;

byteSize('🚗'); // 4
byteSize('Hello World'); // 11


14. Randomly get elements in an array

const randomly = arr => arr[Math.floor(Math.random() * arr.length)];

randomly([1, 3, 5, 7, 9, 11]);


15. 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

This concludes this article about 15 JavaScript functions worth collecting. For more relevant JavaScript function content, please search 123WORDPRESS.COM’s previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • JavaScript functional programming basics
  • An article teaches you JS function inheritance
  • JavaScript Basics Series: Functions and Methods
  • JS function call, apply and bind super detailed method
  • JavaScript function call, apply and bind method case study
  • Detailed explanation of the difference between arrow functions and normal functions in JavaScript
  • JavaScript knowledge: Constructors are also functions
  • Use of JavaScript sleep function
  • Detailed examples of variable and function promotion in JavaScript
  • Summary of 50+ Utility Functions in JavaScript

<<:  MySQL database query performance optimization strategy

>>:  Implementation of nginx flow control and access control

Recommend

React Principles Explained

Table of contents 1. setState() Description 1.1 U...

Browser compatibility summary of common CSS properties (recommended)

Why do we need to summarize the browser compatibi...

Detailed process of installing and configuring MySQL and Navicat prenium

Prerequisite: Mac, zsh installed, mysql downloade...

Implementation of TypeScript in React project

Table of contents 1. Introduction 2. Usage Statel...

Solutions to invalid is Null segment judgment and IFNULL() failure in MySql

MySql Null field judgment and IFNULL failure proc...

MySQL merge and split by specified characters example tutorial

Preface Merging or splitting by specified charact...

Tomcat common exceptions and solution code examples

The company project was developed in Java and the...

How to install mysql5.6 in docker under ubuntu

1. Install mysql5.6 docker run mysql:5.6 Wait unt...

js to implement the snake game with comments

This article example shares the specific code of ...

How to use Webstorm and Chrome to debug Vue projects

Table of contents Preface 1. Create a new Vue pro...

JavaScript - Using slots in Vue: slot

Table of contents Using slots in Vue: slot Scoped...

Detailed explanation of Linx awk introductory tutorial

Awk is an application for processing text files, ...

How to remove the header from the element table

Document hints using the show-header attribute sh...

Background gradient animation effect made by css3

Achieve results Implementation Code html <h1 c...