Home  >  Article  >  Web Front-end  >  11 JS tips worth collecting that are helpful for development

11 JS tips worth collecting that are helpful for development

青灯夜游
青灯夜游forward
2021-03-02 09:40:541452browse

This article will share with you 11 JS tips that are helpful for development. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

11 JS tips worth collecting that are helpful for development

Related recommendations: JavaScript video tutorial

1. Generate a list with random numbers

Array.from({ length: 1000 }, Math.random)
// [ 0.6163093133259432, 0.8877401276499153, 0.4094354756035987, ...] - 1000 items

2. Generate a list with numbers

Array.from({ length: 1000 }, (v, i) => i)
// [0, 1, 2, 3, 4, 5, 6....999]

3. RGB→convert to hexadecimal

const rgb2hex = ([r, g, b]) =>
  `#${(1 << 24) + (r << 16) + (g << 8) + b}`.toString(16).substr(1);

rgb2hex([76, 11, 181]);
// #4c0bb5

4. Convert hexadecimal → RGB

How to convert it back? This is a great way to achieve that goal.

const hex2rgb = hex =>
  [1, 3, 5].map((h) => parseInt(hex.substring(h, h + 2), 16));

hex2rgb("#4c0bb5");
// [76, 11, 181]

5. Odd or even number

Use bitwise operations:

const value = 232;  

if (value & 1) console.log("odd");
else console.log("even");
// even

6. Check for valid URL

const isValidURL = (url) => {
  try {
    new URL(url);
    return true;
  } catch (error) {
    return false;
  }
}

isValidURL(&#39;https://segmentfault.com/u/minnanitkong/articles&#39;)
// true

isValidURL("https//invalidto");
// false

7. Representation of time from past to present

Sometimes we need to print the date 6 minutes ago, but we don’t want a large library to complete it. Here's a small snippet to do just that:

const fromAgo = (date) => {
  const ms = Date.now() - date.getTime();
  const seconds = Math.round(ms / 1000);
  const minutes = Math.round(ms / 60000);
  const hours = Math.round(ms / 3600000);
  const days = Math.round(ms / 86400000);
  const months = Math.round(ms / 2592000000);
  const years = Math.round(ms / 31104000000);

  switch (true) {
    case seconds < 60:
      return `${seconds} second(s) ago"`;
    case minutes < 60:
      return `${minutes} minute(s) ago"`;
    case hours < 24:
      return `${hours} hour(s) ago"`;
    case days < 30:
      return `${days} day(s) ago`;
    case months < 12:
      return `${months} month(s) ago`;
    default:
      return `${years} year(s) ago`;
  }
};

const createdAt = new Date(2021, 0, 5);
fromAgo(createdAt); // 14 day(s) ago;

8. Generating routes with parameters

We do a lot of work when dealing with routes/paths, we always It needs to be acted upon. When we need to generate a path with parameters to push the browser there, generatePath can help us!

const generatePath = (path, obj) =>
    path.replace(/(:[a-z]+)/g, (v) => obj[v.substr(1)]);

const route = "/app/:page/:id";
generatePath(route, {
  page: "products",
  id: 85,
});
// /app/products/123

9. Get parameters from path

const getPathParams = (path, pathMap, serializer) => {
  path = path.split("/");
  pathMap = pathMap.split("/");
  return pathMap.reduce((acc, crr, i) => {
    if (crr[0] === ":") {
      const param = crr.substr(1);
      acc[param] = serializer && serializer[param]
        ? serializer[param](path[i])
        : path[i];
    }
    return acc;
  }, {});
};

getPathParams("/app/products/123", "/app/:page/:id");
// { page: &#39;products&#39;, id: &#39;123&#39; }

getPathParams("/items/2/id/8583212", "/items/:category/id/:id", {
  category: v => [&#39;Car&#39;, &#39;Mobile&#39;, &#39;Home&#39;][v],
  id: v => +v
});
// { category: &#39;Home&#39;, id: 8583212 }

10. Generate path with query string

const getQueryParams = url =>
  url.match(/([^?=&]+)(=([^&]*))/g).reduce((total, crr) => {
    const [key, value] = crr.split("=");
    total[key] = value;
    return total;
  }, {});

getQueryParams("/user?name=Orkhan&age=30");
// { name: &#39;Orkhan&#39;, age: &#39;30&#39; }

Original address: https://dev.to/11-javascript-tips-and-tricks-to-code-like-a-superhero-vol-2-mp6

Author: Orkhan Jafarov

Translation address: https://segmentfault.com/a/1190000039122988

For more programming-related knowledge, please visit: Programming Video! !

The above is the detailed content of 11 JS tips worth collecting that are helpful for development. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete