Write your own code base (implementation and encapsulation of common examples of javascript)

Posted by lando on Wed, 12 Jun 2019 23:12:38 +0200

1. Preface

Because the company's recent projects are busy, there are not so many spare events to write articles, so this article was released a few days later. But it doesn't matter, but when it comes, it always comes.
Well, let's not say much about the others. You should know when you develop, there are many common examples of operations. For example, array de-duplication, keyword highlighting, disruption of the array and so on. These operations, the code generally will not be many, the realization of logic will not be difficult, the following code, I will not explain too much, with comments, I believe you will understand. However, the use of places will be compared, if there is a project where need to be used, if repeated writing, that is, code sink, development efficiency is not needed, reuse is basically copy and paste! This is a very bad habit, you can consider encapsulating some common operations into functions, when calling, just call directly!
Source codes are on github, you want to change or add in the future, you are welcome to star t. ec-do.

2. String operation

2-1 String Space Removal

//Remove blank type 1-all blanks 2-front and back blanks 3-front blanks 4-back blanks
function trim(str,type){
    switch (type){
        case 1:return str.replace(/\s+/g,"");
        case 2:return str.replace(/(^\s*)|(\s*$)/g, "");
        case 3:return str.replace(/(^\s*)/g, "");
        case 4:return str.replace(/(\s*$)/g, "");
        default:return str;
    }
}

2-2 letter case switching

/*type
1:title case   
2: Home capital lowercase
3: toggle case
4: All capitals
5: lowercase
 * */
//changeCase('asdasd',1)
//Asdasd
function changeCase(str,type)
{
    switch(type){
        case 1:return str.replace(/^(\w)(\w+)/,function (v,v1,v2){return v1.toUpperCase()+v2.toLowerCase();});
        case 2:return str.replace(/^(\w)(\w+)/,function (v,v1,v2){return v1.toLowerCase()+v2.toUpperCase();});
        case 3:return str.replace(/^([a-z]+)([A-Z]+)/,function (v,v1,v2){return v1.toUpperCase()+v2.toLowerCase();});
        case 4:return str.toUpperCase();
        case 5:return str.toLowerCase();
        default:return str;
    }
}

2-3 String Cyclic Copy

//RepeatStr (str - > string, count - > number of times)
//repeatStr('123',3)
//"123123123"
function repeatStr(str, count) {
    var text = '';
    for (var i = 0; i < count; i++) {
        text += str;
    }
    return text;
}

2-4 String Replacement

//String substitution (string, character to be replaced, what to replace)
function replaceAll(str,AFindText,ARepText){
   raRegExp = new RegExp(AFindText,"g");
   return str.replace(raRegExp,ARepText);
}

2-5 Replacement*

//ReplceStr (String, Character Format, Replacement Method, Replacement Character (Default*))
function replaceStr(str, regArr, type,ARepText) {
    var regtext = '', Reg = null,replaceText=ARepText||'*';
    //replaceStr('18819322663',[3,5,3],0)
    //188*****663
    //RepatStr is defined above (string circular replication). Attention, everybody.
    if (regArr.length === 3 && type === 0) {
        regtext = '(\\w{' + regArr[0] + '})\\w{' + regArr[1] + '}(\\w{' + regArr[2] + '})'
        Reg = new RegExp(regtext);
        var replaceCount = repeatStr(replaceText, regArr[1]);
        return str.replace(Reg, '$1' + replaceCount + '$2')
    }
    //replaceStr('asdasdasdaa',[3,5,3],1)
    //***asdas***
    else if (regArr.length === 3 && type === 1) {
        regtext = '\\w{' + regArr[0] + '}(\\w{' + regArr[1] + '})\\w{' + regArr[2] + '}'
        Reg = new RegExp(regtext);
        var replaceCount1 = repeatSte(replaceText, regArr[0]);
        var replaceCount2 = repeatSte(replaceText, regArr[2]);
        return str.replace(Reg, replaceCount1 + '$1' + replaceCount2)
    }
    //replaceStr('1asd88465asdwqe3',[5],0)
    //*****8465asdwqe3
    else if (regArr.length === 1 && type == 0) {
        regtext = '(^\\w{' + regArr[0] +  '})'
        Reg = new RegExp(regtext);
        var replaceCount = repeatSte(replaceText, regArr[0]);
        return str.replace(Reg, replaceCount)
    }
    //replaceStr('1asd88465asdwqe3',[5],1,'+')
    //"1asd88465as+++++"
    else if (regArr.length === 1 && type == 1) {
        regtext = '(\\w{' + regArr[0] +  '}$)'
        Reg = new RegExp(regtext);
        var replaceCount = repeatSte(replaceText, regArr[0]);
        return str.replace(Reg, replaceCount)
    }
}

2-6 Detection String

//checkType('165226226326','phone')
//false
//You can expand as needed.
function checkType (str, type) {
    switch (type) {
        case 'email':
            return /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/.test(str);
        case 'phone':
            return /^1[3|4|5|7|8][0-9]{9}$/.test(str);
        case 'tel':
            return /^(0\d{2,3}-\d{7,8})(-\d{1,4})?$/.test(str);
        case 'number':
            return /^[0-9]$/.test(str);
        case 'english':
            return /^[a-zA-Z]+$/.test(str);
        case 'chinese':
            return /^[\u4E00-\u9FA5]+$/.test(str);
        case 'lower':
            return /^[a-z]+$/.test(str);
        case 'upper':
            return /^[A-Z]+$/.test(str);
        default :
            return true;
    }
}

2-7 Detection of Password Strength

//checkPwd('12asdASAD')
//3 (strength grade 3)
function checkPwd(str) {
    var nowLv = 0;
    if (str.length < 6) {
        return nowLv
    }
    ;
    if (/[0-9]/.test(str)) {
        nowLv++
    }
    ;
    if (/[a-z]/.test(str)) {
        nowLv++
    }
    ;
    if (/[A-Z]/.test(str)) {
        nowLv++
    }
    ;
    if (/[\.|-|_]/.test(str)) {
        nowLv++
    }
    ;
    return nowLv;
}

2-8 random code( To String Details)

//count range 0-36

//randomNumber(10)
//"2584316588472575"

//randomNumber(14)
//"9b405070dd00122640c192caab84537"

//Math.random().toString(36).substring(2);
//"83vhdx10rmjkyb9"
function randomNumber(count){
   return Math.random().toString(count).substring(2);
}

2-9 Find Strings

Maybe the title will be a bit misleading. Let me briefly describe a requirement to find out the number of'blog'in the string'sad44654 blog 5A 1sd67as 9dablog 4S 5D 16zxc4sdweasjk blog wqepaskdkblog gahseiuadbhjcibloyeajzxkcabuyizwezc967'. The code is as follows

function countStr (str,strSplit){
    return str.split(strSplit).length-1
}
var strTest='sad44654blog5a1sd67as9dablog4s5d16zxc4sdweasjkblogwqepaskdkblogahseiuadbhjcibloguyeajzxkcabloguyiwezxc967'
//countStr(strTest,'blog')
//6

3. Array operations

3-1 array de-weighting

This method is too much, I wrote earlier articles.( js array operation -- using iteration instead of for loop,js keyword discoloration, array scrambling, implementation and encapsulation of array de-duplication ) It was also mentioned that today I'm going to write a method that I haven't used before.

//ES6's new Set data structure is similar to an array, but the elements are unique, and its constructor can accept an array as a parameter.
//let arr=[1,2,1,2,6,3,5,69,66,7,2,1,4,3,6,8,9663,8]
//let set = new Set(array);
//{1,2,6,3,5,69,66,7,4,8,9663}
//In ES6, Array adds a static method from, which converts objects like arrays into arrays.
//Array.from(set)
//[1,2,6,3,5,69,66,7,4,8,9663]
function removeRepeatArray(arr){
    return Array.from(new Set(arr))
}

3-2 Array Sequence Disturbance

function upsetArr(arr){
    return arr.sort(function(){ return Math.random() - 0.5});
}

3-3 Array Maximum and Minimum

//The encapsulation of this block is mainly for arrays of digital type.
function maxArr(arr){
    return Math.max.apply(null,arr);
}
function minArr(arr){
    return Math.min.apply(null,arr);
}

3-4 array summation, average

//The encapsulation of this block is mainly for arrays of digital type.
//Summation
function sumArr(arr){
    var sumText=0;
    for(var i=0,len=arr.length;i<len;i++){
        sumText+=arr[i];
    }
    return sumText
}
//Average, decimal point may have a lot of bits, here do not deal with, deal with the use is not flexible!
function covArr(arr){
    var sumText=sumArr(arr);
    var covText=sumText/length;
    return covText
}

3-5 Random Access to Elements from Arrays

//randomOne([1,2,3,6,8,5,4,2,6])
//2
//randomOne([1,2,3,6,8,5,4,2,6])
//8
//randomOne([1,2,3,6,8,5,4,2,6])
//8
//randomOne([1,2,3,6,8,5,4,2,6])
//1
function randomOne(arr) {
    return arr[Math.floor(Math.random() * arr.length)];
}

3-6 Returns the number of occurrences of an element in an array (string)

//getEleCount('asd56+asdasdwqe','a')
//3
//getEleCount([1,2,3,4,5,66,77,22,55,22],22)
//2
function getEleCount (obj, ele) {
    var num = 0;
    for (var i = 0, len = obj.length; i < len; i++) {
        if (ele == obj[i]) {
            num++;
        }
    }
    return num;
}

3-7 Returns the most elements and occurrences of arrays (strings)

//Arr, rank - > length, default array length, rank type, sort mode, default descending order
function getCount(arr, rank,ranktype){ 
    var obj = {}, k, arr1 = []
    //Record the number of occurrences of each element
    for (var i = 0, len = arr.length; i < len; i++) {
        k = arr[i];
        if (obj[k]) {
            obj[k]++;
        }
        else {
            obj[k] = 1;
        }
    }
    //Save the result {el-'element', count-number of occurrences}
    for (var o in obj) {
        arr1.push({el: o, count: obj[o]});
    }
    //Sorting (descending)
    arr1.sort(function (n1, n2) {
        return n2.count - n1.count
    });
    //If ranktype is 1, the array is in ascending order and inverted
    if(ranktype===1){
        arr1=arr1.reverse();
    }
    var rank1 = rank || arr1.length;
    return arr1.slice(0,rank1);
}

getCount([1,2,3,1,2,5,2,4,1,2,6,2,1,3,2])
By default, return the number of occurrences of all elements

getCount([1,2,3,1,2,5,2,4,1,2,6,2,1,3,2],3)
Reference (rank=3), returning only the first three ranks of occurrences

getCount([1,2,3,1,2,5,2,4,1,2,6,2,1,3,2],null,1)
Rank type = 1, rank = null, ascending order returns the number of occurrences of all elements

getCount([1,2,3,1,2,5,2,4,1,2,6,2,1,3,2],3,1)
Reference (rank=3, ranktype=1) returns only the first three of the occurrence order (ascending order)

3-8 Gets an array of n1-n2 Subscripts

//getArrayNum([0,1,2,3,4,5,6,7,8,9],5,9)
//[5, 6, 7, 8, 9]

//getArrayNum([0,1,2,3,4,5,6,7,8,9],2) does not pass the second parameter and returns the element from n1 to the end of the array by default.
//[2, 3, 4, 5, 6, 7, 8, 9]
function getArrayNum(arr,n1,n2){
    var arr1=[],len=n2||arr.length-1;
    for(var i=n1;i<=len;i++){
        arr1.push(arr[i])
    }
    return arr1;
}

3-9 filter array

/Deleted value'val'Array elements
//removeArrayForValue(['test','test1','test2','test','aaa'],'test','%')
//["aaa"] with'test'deleted
    
//removeArrayForValue(['test','test1','test2','test','aaa'],'test')
//["test1," "test2," "aaa"]// The value of the array element is all equal to'test'before it is deleted
function removeArrayForValue(arr,val,type){
    arr.filter(function(item){return type==='%'?item.indexOf(val)!==-1:item!==val})
}

4. Basic DOM operations

This part of the code actually refers to some functions of jquery, the only difference is that the call is not used, the parameters are the same.
For example, the chestnuts below

//Setting Object Content
jquery: $('#xxx').html('hello world');
//Now: html(document.getElementById('xxx'),'hello world')
//Getting object content
jquery: $('#xxx').html();
//Now: html(document.getElementById('xxx'))

4-1 checks whether the object has any class name

function hasClass(obj,classStr){ 
    var arr=obj.className.split(/\s+/); //This regular expression is because classes can have multiple classes to determine whether they contain 
    return (arr.indexOf(classStr)==-1)?false:true;
},

4-2 Add Class Name

function addClass(obj,classStr){
    if (!this.hasClass(obj,classStr)){obj.className += " " + classStr};
},

4-3 Delete class names

function removeClass(obj,classStr){
    if (this.hasClass(obj,classStr)) {
        var reg = new RegExp('(\\s|^)' + classStr + '(\\s|$)');
        obj.className = obj.className.replace(reg, '');
    }
},

4-4 Replacement Class Name ("Substituted Class Name", "Substituted Class Name")

function replaceClass(obj,newName,oldName) {
    removeClass(obj,oldName);
    addClass(obj,newName);
}

4-5 Getting Brother Nodes

function siblings(obj){
    var a=[];//Define an array to store o's sibling elements 
    var p=obj.previousSibling; 
    while(p){//The brothers who took o first judged whether there was a previous brotherhood element, and if there was one, they performed p to indicate previous Sibling. 
        if(p.nodeType===1){ 
        a.push(p); 
        } 
        p=p.previousSibling//Finally, assign the last node to p 
    } 
    a.reverse()//Reverse the order so that the order of the elements is in order. 
    var n=obj.nextSibling;//Take o's younger brother again 
    while(n){//Judging whether there is the next brother node n means nextSibling 
        if(n.nodeType===1){ 
            a.push(n); 
        } 
        n=n.nextSibling; 
    }
    return a;
},

4-6 Setting Style

function css(obj,json){
    for(var attr in json){
        obj.style[attr]=json[attr];
    }
}

4-7 Setting Text Content

function html(obj){
    if(arguments.length==0){
        return this.innerHTML;
    }
    else if(arguments.length==1){
        this.innerHTML=arguments[0];
    }
}

4-8 Display Hiding


function show(obj){
    obj.style.display="";
}
function hide(obj){
    obj.style.display="none";
}

5. Other operations

5-1cookie

//cookie
//Setting cookie s
function setCookie(name,value,iDay){
    var oDate=new Date();
    oDate.setDate(oDate.getDate()+iDay);
    document.cookie=name+'='+value+';expires='+oDate;
}
//Getting cookie s
function getCookie(name){
    var arr=document.cookie.split('; ');
    for(var i=0;i<arr.length;i++){
        var arr2=arr[i].split('=');
        if(arr2[0]==name)
        {
            return arr2[1];
        }
    }
    return '';
}
//delete cookie
function removeCookie(name){
    setCookie(name,1,-1);
}

5-2 Clears an empty property in an object

//filterParams({a:"",b:null,c:"010",d:123})
//Object {c: "010", d: 123}
function filterParams(obj){
    let _newPar = {};
    for (let key in obj) {
        if ((obj[key] === 0 || obj[key]) && obj[key].toString().replace(/(^\s*)|(\s*$)/g, '') !== '') {
            _newPar[key] = obj[key];
        }
    }
    return _newPar;
}

5-3 Cash Uppercase Conversion Function

//upDigit(168752632)
//"Renminbi 100 million Lu Biao pick up Wu Wan Bian Lu Bian three pick up Bian integrity"
//upDigit(1682)
//"Renminbi is one hundred and fifty yuan, and Lu is one hundred and fifty yuan."
//upDigit(-1693)
//"One hundred yuan in arrears to Renminbi and three yuan in arrears to Lubai"
function upDigit(n)   
{  
    var fraction = ['horn', 'branch','Li'];  
    var digit = ['Zero', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine'];  
    var unit = [ ['element', 'ten thousand', 'Billion'], ['', 'Ten', 'Bai', 'Thousand']  ];  
    var head = n < 0? 'Debt to Renminbi': 'RMB';  
    n = Math.abs(n);  
    var s = '';  
    for (var i = 0; i < fraction.length; i++)   
    {
        s += (digit[Math.floor(n * 10 * Math.pow(10, i)) % 10] + fraction[i]).replace(/Zero./, ''); 
    } 
    s = s || 'whole';  
    n = Math.floor(n);  
    for (var i = 0; i < unit[0].length && n > 0; i++)   
    {  
        var p = '';  
        for (var j = 0; j < unit[1].length && n > 0; j++)   
        {  
            p = digit[n % 10] + unit[1][j] + p; 
            n = Math.floor(n / 10);
        }
        //s = p.replace(/(zero.)* zero $/,''). replace(/^$/,'zero') + unit[0][i] + s; 
        s = p+ unit[0][i] + s;
    }
    return head + s.replace(/(Zero.)*Zero element/, 'element').replace(/(Zero.)+/g, 'Zero').replace(/^whole $/, 'Zero Yuan Integral');
} 

5-4 Get and set url parameters

//Getting url parameters
//getUrlPrmt('segmentfault.com/write?draftId=122000011938')
//Object{draftId: "122000011938"}
function getUrlPrmt(url) {
    url = url ? url : window.location.href;
    let _pa = url.substring(url.indexOf('?') + 1), _arrS = _pa.split('&'), _rs = {};
    for (let i = 0, _len = _arrS.length; i < _len; i++) {
        let pos = _arrS[i].indexOf('=');
        if (pos == -1) {
            continue;
        }
        let name = _arrS[i].substring(0, pos), value = window.decodeURIComponent(_arrS[i].substring(pos + 1));
        _rs[name] = value;
    }
    return _rs;
}

//Setting url parameters
//setUrlPrmt({'a':1,'b':2})
//a=1&b=2
function setUrlPrmt(obj) {
    let _rs = [];
    for (let p in obj) {
        if (obj[p] != null && obj[p] != '') {
            _rs.push(p + '=' + obj[p])
        }
    }
    return _rs.join('&');
}

5-5 Random Returns a Range of Numbers


function randomNumber(n1,n2){
    //randomNumber(5,10)
    //Returns 5-10 random integers, including 5,10
    if(arguments.length===2){
        return Math.round(n1+Math.random()*(n2-n1));
    }
    //randomNumber(10)
    //Returns 0-10 random integers, including 0,10
    else if(arguments.length===1){
        return Math.round(Math.random()*n1)
    }
    //randomNumber()
    //Returns a random integer of 0-255, including 0,255
    else{
        return Math.round(Math.random()*255)
    }  
}

5-6 Following in to produce colour

function randomColor(){
    //Random Number is the function defined above
    //Writing 1
    return 'rgb(' + randomNumber(255) + ',' + randomNumber(255) + ',' + randomNumber(255) + ')';
    
    //Writing 2
    return '#'+Math.random().toString(16).substring(2).substr(0,6);
    
    //Writing 3
    var color='#';
    for(var i=0;i<6;i++){
        color+='0123456789abcdef'[randomNumber(15)];
    }
    return color;
}

// Sometimes there are problems with this writing. Everybody should pay attention to it.
//Math.floor(Math.random()*0xffffff).toString(16);

5-7 Date Date Date Date Date Time Part

//Countdown to a certain time
//getEndTime('2017/7/22 16:0:0')
//"6 days, 2 hours, 28 minutes, 20 seconds"
function getEndTime(endTime){
    var startDate=new Date();  //Start time, current time
    var endDate=new Date(endTime); //End time, need to pass in time parameter
    var t=endDate.getTime()-startDate.getTime();  //Milliseconds of time difference
    var d=0,h=0,m=0,s=0;
    if(t>=0){
      d=Math.floor(t/1000/3600/24);
      h=Math.floor(t/1000/60/60%24);
      m=Math.floor(t/1000/60%60);
      s=Math.floor(t/1000%60);
    } 
    return "Remaining time"+d+"day "+h+"hour "+m+" Minute"+s+" second";
}

5-8 adapted rem

There are many ways to adapt, so I'll write my own way. You can also go to a question I answered to see more detailed instructions! Mobile Adaptation Problem

function getFontSize(){
    var doc=document,win=window;
    var docEl = doc.documentElement,
    resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize',
    recalc = function () {
        var clientWidth = docEl.clientWidth;
        if (!clientWidth) return;
        //If the screen is larger than 750 (750 is set according to my rendering, specific numerical reference rendering), set clientWidth=750 to prevent font-size from exceeding 100px.
        if(clientWidth>750){clientWidth=750}
        //Set the font-size size of the root element
        docEl.style.fontSize = 100 * (clientWidth / 750) + 'px';
    };
    //Trigger function when screen size changes or screen switching
    win.addEventListener(resizeEvt, recalc, false);
    //Trigger function when document loading is complete
    doc.addEventListener('DOMContentLoaded', recalc, false);
}
//The way to use it is very simple. For example, on the effect map, there is a picture. The width and height are 100 px.
//Style writing is
img{
    width:1rem;
    height:1rem;
}
//For example, on devices with a screen width greater than or equal to 750px, 1rem=100px; the image display is 100px in width and height.
//For example, on the iPhone 6 (screen width: 375), 375/750*100=50px; that is, 1rem=50px; the image shows that the width and height are 50px;

6. Packaging

Write so many operations, small partners should find a problem, there are too many global functions

//In this way, encapsulation of several operations adds several global functions, polluting global variables, and global variables should be avoided as far as possible in development. Needless to say, if a project is developed by several people, it is likely to cause naming conflicts.

function setUrlPrmt(obj){..}
function getUrlPrmt(url){..}
function upsetArr(obj){..}


//So, the recommended encapsulation posture is
var myJS={
    setUrlPrmt:function(obj){..},
    getUrlPrmt:function(url){..},
    upsetArr:function(arr){..},
}
//In this way, even if others write such functions, there will be no conflict. There's only one global variable, and there won't be many others!
var otherJS={
    setUrlPrmt:function(obj){..},
    getUrlPrmt:function(url){..},
    upsetArr:function(arr){..},
}


//Finally, the effect of encapsulation is
var myJS={
    //String space removal
    trim:function(obj){..},
    //Alphabet case switching
    changeCase:function(obj){..},
    //Cyclic copying of strings
    repeatStr:function(str){..},
    .....
}

//If it is the modular development of es6, you can also
let myJS={
    //String space removal
    trim:function(obj){..},
    //Alphabet case switching
    changeCase:function(obj){..},
    //Cyclic copying of strings
    repeatStr:function(str){..},
    .....
}
//Exposure module, the way in which you can also use es6 way to achieve, at least a little less code!
export {myJS}

There may be some doubts from small partners. It is a bit troublesome to encapsulate and invoke in this way. Why not encapsulate directly on the prototype and make it convenient to invoke. Like the chestnuts below!

String.prototype.trim=function(type){
    switch (type){
        case 1:return this.replace(/\s+/g,"");
        case 2:return this.replace(/(^\s*)|(\s*$)/g, "");
        case 3:return this.replace(/(^\s*)/g, "");
        case 4:return this.replace(/(\s*$)/g, "");
        default:return this;
    }
}
//'  12345 6 8 96  '.trim(1)
//"123456896"
//It is more convenient to call trim ('123456896', 1).
//However, this is not recommended, which pollutes the String of native objects, and the String created by others will be polluted, causing unnecessary overhead.
//What's more, in case the original method is renamed again, the original method will be overwritten.
//String.prototype.substr=function(){console.log('asdasd')}  
//'asdasdwe46546'.substr()
//asdasd 
//What's the function of substr method? You should know, you can go to w3c to see if you don't know.

So the modification of the prototype of native object is not recommended! At least a lot of companies prohibit such operations!

7. Summary

This article has been written for a long time, several hours, because I wrote this article, I also changed my previous code, because I used to write code, the function is the same, the code is more, and now I want to write while rewriting, but also test myself (before the code for many loops, now there are many concise writing instead). In addition, the company has been busy recently, so it took several days to finish this article.
Source codes are on github, you want to change or add in the future, you are welcome to star t. ec-do.
I encapsulate this by myself, not because I have the habit of making wheels, but because:
1. All of them are commonly used, but there are scattered small examples. There are basically no plug-ins on the Internet.
2. Because there are scattered small instances involving string, array, object and other types, even if plug-ins are found, more than one plug-in is likely to be introduced in the project.
3. It's all simple code, and it's easy to encapsulate. Maintenance is also simple.
No more nonsense, the above is just my own development in common use, hoping to help small partners, the most ideal is that this article can play a role of throwing a brick to attract jade, that is to say, if you think there are any other operations are commonly used, or where I think I write poorly, also welcome to point out that let everyone help each other, learn from each other.

Topics: Javascript JSON JQuery github Mobile