“There is no way in the world, but when more people walk, it becomes a road.” There is no smooth road on the road of code, but after many experiences, it may become a road.

preface

Such as the introduction, development will often meet many generic code, such as mobile phone number, email verification, access to and operation url parameters, cookies, etc., however, wrap the commonly used method of library does not see more, and these methods are associated with the project experience of himself, is likely to extend some useful methods, so there are still necessary to achieve them.

So what we’re trying to do here isThe topic, friends can refer to the author’s ideas, to achieve their own.

Problems to be solved

Before implementing this library, the following issues need to be addressed

  1. Need to haveAppropriate build tools, convenient for us to package the code, and easy to debug;
  2. Pay attention toCode quality and development efficiency, have type inference and static check ability;
  3. Easy to use API, it is best to remember at a glance;

In summary, the author chooses Rollup + Webpack + typeScript + Jest to build and debug the code. If you are not familiar with these tools, you can check the corresponding official website for documentation. You can also download the source code based on my github address.

Rollup

  • A JavaScript module wrapper that compiles small pieces of code into large, complex pieces. It allows us to quickly package code into modules such as CommonJS, ES, and UMD, as well as statically analyze the code to weed out unused code.

Webpack

  • Webpack is also a module packer, which is more powerful, but rollup is better than Webpack for packaging and encapsulating JS libraries. You don’t have to use WebPack, but you can quickly set up a local server, debug while writing code, and move HTML files.

TypeScript

  • TypeScript is a free and open source programming language developed by Microsoft. It is a superset of JavaScript that extends the syntax of JavaScript and combines the static checking and type inference capabilities of development tools to help us write more rigorous and reliable code.

Jest

  • Jest is a testing framework from Facebook that can be easily configured to verify that the methods we write are reliable.

A couple of common methods

Get URL parameters

/** * @param gets all parameters of the current URL if the parameter is null. * when @param parameter is 1, the specified parameter of the current URL is obtained; * if @param is 2 and the second parameter is not true, get the specified parameter of the specified URL; * if @param is 2 and the second parameter is true, get all the parameters of the specified URL; * /
get() : string | Object {
  let args = arguments,
  len = args.length,
  url: string;

  if (len == 1 || len == 0) {
    url = location.search;
  } else {
    url = args[0];
  }
  url = url.substring(url.indexOf('? ') + 1);
  let arr = url.split('&'),
  obj: string | Object = {};

  this.each(arr, (v, i) = >{
    if (v.indexOf('=') != - 1) {
      let arg = v.split('='),
      key = decodeURIComponent(arg[0]),
      val = decodeURIComponent(arg[1]); obj[key] = val; }})return len == 1 || (len == 2 && args[1]! = =true)? obj[len ==1 ? args[0] : args[1]] | |' ': obj;
}
Copy the code

Getting URL parameters is a very frequent operation in front-end development, especially after the separation of the front and back ends. Here we use a very simple GET name, which can get the current URL or all specified parameters of the specified URL.

Example:

Note: Since the package name is JS-ToolKits, the default abbreviation is TKS, same below

tks.get();// All parameters of the current URL
tks.get('name');// The current URL specifies a parameter
tks.get('www.baidu.com?xx=1'.'xx');// Specify the url, specify the parameters
tks.get('www.baidu.com?xx=1&yy=2&zz=3'.true);// Specify the url, all parameters
Copy the code

Iterate over objects and arrays

/ * * * each iterate through group and Object * @ param obj {Object | Array} traverse Object * @ param callback Function callback Function, attach the first parameter to val, the second as the key, in contrast to the jquery here * /
each(obj: Array < any > , callback: Function) : Array < any > {
  let length: number,
  i: number | string = 0;

  if (isArrayLike(obj)) {
    length = obj.length;
    for (; i < length; i++) {
      if (callback.call(obj[i], obj[i], i) === false) {
        break; }}}else {
    for (i in obj) {
      if (callback.call(obj[i], obj[i], i) === false) {
        break; }}}return obj;
}
Copy the code

This is a direct reference to the jquery each method, but the difference is that the order of value and index is adjusted according to the custom, which is very practical when traversing groups of numbers and objects.

Example:

tks.each({ aa: 1.bb: 2.cc: 3 },(v, i) = >{
  console.log(v, i);
})
tks.each([1.3.5.7.9], (v, i) = >{
  console.log(v, i);
})
Copy the code

Common string detection

@param type {String} Type * @param STR {String} String to be tested */
test(type: string, str: string) : Boolean {
  switch (type) {
  case 'phone':
    return /^1[3456789]\d{9}$/.test(str);
  case 'email':
    return /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/.test(str);
  case 'json':
    if (typeofstr ! ='string') {
      return false;
    }

    try {
      JSON.parse(str);
      return true;
    } catch(e) {
      return false;
    }
  default:
    return false; }}Copy the code

Handling string detection is also a common operation, especially in form submission, where switching matches types is also easy to extend directly.

Example:

tks.test('phone'.'18888888888');//true
tks.test('email'.'[email protected]');//true
tks.test('email'.'123456');//false
tks.test('json'.'{"isJson":"true"}');//true
Copy the code

The above list of several common methods, the design of the idea is simple and clear, there are many specific ways to achieve, vary from person to person.

Trim (string whitespace), param(object to URL parameter), storage(operation sessionStorage, localStorage, cookie), etc

The last

This library is not perfect, the author is still a little groping, interested partners can refer to the implementation. If you have any help, please star, or give a “like” to the article. If you have any suggestions or questions, please feel free to comment.