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

MySQL multi-table query detailed explanation

Eating well and getting enough rest sounds simple...

Quickly master how to get started with Vuex state management in Vue3.0

Vuex is a state management pattern developed spec...

MySQL Constraints Super Detailed Explanation

Table of contents MySQL Constraint Operations 1. ...

Summary of MySql index, lock, and transaction knowledge points

This article summarizes the knowledge points of M...

How to view the running time of MySQL statements through Query Profiler

The previous article introduced two methods to ch...

Detailed explanation of 5 solutions for CSS intermediate adaptive layout

Preface When making a page, we often encounter co...

Let's talk about MySQL joint query in detail

Table of contents Union query 1. Query the ID and...

Vue implements interface sliding effect

This article example shares the specific code of ...

MySQL 8.0.11 installation tutorial with pictures and text

There are many tutorials on the Internet, and the...

Advanced and summary of commonly used sql statements in MySQL database

This article uses examples to describe the common...

CSS -webkit-box-orient: vertical property lost after compilation

1. Cause The requirement is to display two lines,...

How to check PCIe version and speed in Linux

PCIE has four different specifications. Let’s tak...

How to check if a table exists in MySQL and then delete it in batches

1. I searched for a long time on the Internet but...

How to set an alias for a custom path in Vue

How to configure custom path aliases in Vue In ou...