编程知识 cdmana.com

Common tools and methods of front-end JS (Collection)

var ua = window.navigator.userAgent.toLowerCase();
/**
 *  front end JS Common tools and methods
 *  @class  Tools
 */
export   default   class   Tools  {
   /**
   * 1. Is it a mailbox
   *  @method   isEmail
   *  @static  Tools
   *  @param   {String}   s   Email address to be judged
   *  @returns   {Boolean}
   */
   static   isEmail  ( s ) {
     return  / ^ ([ a-zA-Z0-9_- ]) + @ ([ a-zA-Z0-9_- ]) + (( . [ a-zA-Z0-9_- ] {2,3} ) {1,2} ) $ / . test ( s )
  }
 
   /**
   * 2. Phone number
   *  @method   isMobile
   *  @static  Tools
   *  @param   {String}   s  
   *  @returns   {Boolean}
   */
   static   isMobile  ( s ) {
     return  / ^ 1 [ 0-9 ] {10} $ / . test ( s )
  }
 
   //3. Phone number
   static   isPhone  = ( s =>  {
     return  / ^ ([ 0-9 ] {3,4} - ) ? [ 0-9 ] {7,8} $ / . test ( s )
  }
 
   //4. whether url Address
   static   isURL  = ( s =>  {
     return  / ^ http [ s ] ? : \/\/ . * / . test ( s )
  }
 
   //5. String or not
   static   isString  ( o ) {
     return   Object . prototype . toString . call ( o ). slice ( 8 , - 1 ) ===  'String'
  }
 
   //6. Is it a number
   static   isNumber  ( o ) {
     return   Object . prototype . toString . call ( o ). slice ( 8 , - 1 ) ===  'Number'
  }
 
   //7. whether boolean
   static   isBoolean  ( o ) {
     return   Object . prototype . toString . call ( o ). slice ( 8 , - 1 ) ===  'Boolean'
  }
 
   //8. Is it a function
   static   isFunction  = ( o =>  {
     return   Object . prototype . toString . call ( o ). slice ( 8 , - 1 ) ===  'Function'
  }
 
   //9. Is it null
   static   isNull  = ( o =>  {
     return   Object . prototype . toString . call ( o ). slice ( 8 , - 1 ) ===  'Null'
  }
 
   //10. whether undefined
   static   isUndefined  = ( o =>  {
     return   Object . prototype . toString . call ( o ). slice ( 8 , - 1 ) ===  'Undefined'
  }
 
   //11. Whether the object is
   static   isObj  = ( o =>  {
     return   Object . prototype . toString . call ( o ). slice ( 8 , - 1 ) ===  'Object'
  }
 
   //12. Whether array
   static   isArray  = ( o =>  {
     return   Object . prototype . toString . call ( o ). slice ( 8 , - 1 ) ===  'Array'
  }
 
   //13. Is it time
   static   isDate  = ( o =>  {
     return   Object . prototype . toString . call ( o ). slice ( 8 , - 1 ) ===  'Date'
  }
 
   //14. Is it regular
   static   isRegExp  = ( o =>  {
     return   Object . prototype . toString . call ( o ). slice ( 8 , - 1 ) ===  'RegExp'
  }
 
   //15. Wrong object
   static   isError  = ( o =>  {
     return   Object . prototype . toString . call ( o ). slice ( 8 , - 1 ) ===  'Error'
  }
 
   //16. whether Symbol function
   static   isSymbol  = ( o =>  {
     return   Object . prototype . toString . call ( o ). slice ( 8 , - 1 ) ===  'Symbol'
  }
 
   //17. whether Promise object
   static   isPromise  = ( o =>  {
     return   Object . prototype . toString . call ( o ). slice ( 8 , - 1 ) ===  'Promise'
  }
 
   // whether Set object
   static   isSet  = ( o =>  {
     return   Object . prototype . toString . call ( o ). slice ( 8 , - 1 ) ===  'Set'
  }
 
   //19. Is it a wechat browser
   static   isWeiXin  () {
     return   ua . match ( /microMessenger/ i ) ==  'micromessenger'
  }
 
   //20. Is it mobile
   static   isDeviceMobile  = ()  =>  {
     return  /android | webos | iphone | ipod | balckberry/ i . test ( ua )
  }
 
   //21. Whether it is QQ browser
   static   isQQBrowser  = ()  =>  {
     return  !! ua . match ( /mqqbrowser | qzone | qqbrowser | qbwebviewtype/ i )
  }
 
   //22. Is it a reptile
   static   isSpider  = ()  =>  {
     return  /adsbot | googlebot | bingbot | msnbot | yandexbot | baidubot | robot | careerbot | seznambot | bot | baiduspider | jikespider | symantecspider | scannerlwebcrawler | crawler | 360spider | sosospider | sogou web sprider | sogou orion spider/ . test ( ua )
  }
 
   //23. whether ios
   static   isIos  = ()  =>  {
     var   u  =  navigator . userAgent ;
     if  ( u . indexOf ( 'Android' ) > - 1  ||  u . indexOf ( 'Linux' ) > - 1 ) {   // The android mobile phone
       return   false
    }  else   if  ( u . indexOf ( 'iPhone' ) > - 1 ) { // Apple mobile phone
       return   true
    }  else   if  ( u . indexOf ( 'iPad' ) > - 1 ) { //iPad
       return   false
    }  else   if  ( u . indexOf ( 'Windows Phone' ) > - 1 ) { //winphone mobile phone
       return   false
    }  else  {
       return   false
    }
  }
 
   //24. Is it PC End
   static   isPC  = ()  =>  {
     var   userAgentInfo  =  navigator . userAgent ;
     var   Agents  = [ "Android" "iPhone" "SymbianOS" "Windows Phone" "iPad" "iPod" ];
     var   flag  =  true ;
     for  ( var   v  =  0 v  <  Agents . length v ++) {
       if  ( userAgentInfo . indexOf ( Agents [ v ]) >  0 ) {
         flag  =  false ;
         break ;
      }
    }
     return   flag ;
  }
 
   //25. Remove html label
   static   removeHtmltag  = ( str =>  {
     return   str . replace ( /< [^ > ] + >/ g '' )
  }
 
   //26. obtain url Parameters
   static   getQueryString  = ( name =>  {
     const   reg  =  new   RegExp ( '(^|&)'  +  name  +  '=([^&]*)(&|$)' 'i' );
     const   search  =  window . location . search . split ( '?' )[ 1 ] ||  '' ;
     const   r  =  search . match ( reg ) || [];
     return   r [ 2 ];
  }
 
   //27. Dynamic introduction js
   static   injectScript  = ( src =>  {
     const   s  =  document . createElement ( 'script' );
     s . type  =  'text/javascript' ;
     s . async  =  true ;
     s . src  =  src ;
     const   t  =  document . getElementsByTagName ( 'script' )[ 0 ];
     t . parentNode . insertBefore ( s t );
  }
 
   //28. according to url Address download
   static   download  = ( url =>  {
     var   isChrome  =  ua . indexOf ( 'chrome' ) > - 1 ;
     var   isSafari  =  ua . indexOf ( 'safari' ) > - 1 ;
     if  ( isChrome  ||  isSafari ) {
       var   link  =  document . createElement ( 'a' );
       link . href  =  url ;
       if  ( link . download  !==  undefined ) {
         var   fileName  =  url . substring ( url . lastIndexOf ( '/' ) +  1 url . length );
         link . download  =  fileName ;
      }
       if  ( document . createEvent ) {
         var   e  =  document . createEvent ( 'MouseEvents' );
         e . initEvent ( 'click' true true );
         link . dispatchEvent ( e );
         return   true ;
      }
    }
     if  ( url . indexOf ( '?' ) === - 1 ) {
       url  +=  '?download' ;
    }
     window . open ( url '_self' );
     return   true ;
  }
 
   //29.el Whether to include class
   static   hasClass  = ( el className =>  {
     let   reg  =  new   RegExp ( '(^| \\ s)'  +  className  +  '( \\ s|$)' )
     return   reg . test ( el . className )
  }
 
   //30.el Add a class
   static   addClass  ( el className ) {
     if  ( hasClass ( el className )) {
       return
    }
     let   newClass  =  el . className . split ( ' ' )
     newClass . push ( className )
     el . className  =  newClass . join ( ' ' )
  }
 
   //31.el Get rid of something class
   static   removeClass  ( el className ) {
     if  (! hasClass ( el className )) {
       return
    }
     let   reg  =  new   RegExp ( '(^| \\ s)'  +  className  +  '( \\ s|$)' 'g' )
     el . className  =  el . className . replace ( reg ' ' )
  }
 
   //32. Get the coordinates of the scroll
   static   getScrollPosition  ( el  =  window ) {
     return  {
       x:   el . pageXOffset  !==  undefined  ?  el . pageXOffset  :  el . scrollLeft ,
       y:   el . pageYOffset  !==  undefined  ?  el . pageYOffset  :  el . scrollTop
    }
  }
 
   //33. Scroll to top
   static   scrollToTop  () {
     const   c  =  document . documentElement . scrollTop  ||  document . body . scrollTop ;
     if  ( c  >  0 ) {
       window . requestAnimationFrame ( scrollToTop );
       window . scrollTo ( 0 c  -  c  /  8 );
    }
  }
 
   //34.el Whether it's within the scope of the viewport
   static   elementIsVisibleInViewport  ( el partiallyVisible  =  false ) {
     const  {  top left bottom right  } =  el . getBoundingClientRect ();
     const  {  innerHeight innerWidth  } =  window ;
     return   partiallyVisible
      ? (( top  >  0  &&  top  <  innerHeight ) || ( bottom  >  0  &&  bottom  <  innerHeight )) &&
      (( left  >  0  &&  left  <  innerWidth ) || ( right  >  0  &&  right  <  innerWidth ))
      :  top  >=  0  &&  left  >=  0  &&  bottom  <=  innerHeight  &&  right  <=  innerWidth ;
  }
 
   //35. Shuffle algorithm random
   static   shuffle  ( arr ) {
     var   result  = [],
       random ;
     while  ( arr . length  >  0 ) {
       random  =  Math . floor ( Math . random () *  arr . length );
       result . push ( arr [ random ])
       arr . splice ( random 1 )
    }
     return   result ;
  }
 
   //36. Hijack pasteboard
   static   copyTextToClipboard  = ( value =>  {
     var   textArea  =  document . createElement ( "textarea" );
     textArea . style . background  =  'transparent' ;
     textArea . value  =  value ;
     document . body . appendChild ( textArea );
     textArea . select ();
     try  {
       var   successful  =  document . execCommand ( 'copy' );
    }  catch  ( err ) {
       console . log ( 'Oops, unable to copy' );
    }
     document . body . removeChild ( textArea );
  }
 
   //37. Set of judgment types
   static   checkStr  = ( str type =>  {
     switch  ( type ) {
       case   'phone' :    // Phone number
         return  / ^ 1 [ 3|4|5|6|7|8|9 ][ 0-9 ] {9} $ / . test ( str );
       case   'tel' :      // Landline
         return  / ^ ( 0\d {2,3} -\d {7,8} )( -\d {1,4} ) ? $ / . test ( str );
       case   'card' :     // Id card
         return  / ( ^ \d {15} $ ) | ( ^ \d {18} $ ) | ( ^ \d {17} ( \d | X | x ) $ ) / . test ( str );
       case   'pwd' :      // The password begins with a letter , The length is in 6~18 Between , Can only contain letters 、 Numbers and underscores
         return  / ^ [ a-zA-Z ] \w {5,17} $ / . test ( str )
       case   'postal' :   // Postal Code
         return  / [ 1-9 ] \d {5} (?! \d ) / . test ( str );
       case   'QQ' :       //QQ Number
         return  / ^ [ 1-9 ][ 0-9 ] {4,9} $ / . test ( str );
       case   'email' :    // mailbox
         return  / ^ [ \w- ] + ( \. [ \w- ] + ) * @ [ \w- ] + ( \. [ \w- ] + ) + $ / . test ( str );
       case   'money' :    // amount of money ( decimal point 2 position )
         return  / ^ \d * (?: \. \d {0,2} ) ? $ / . test ( str );
       case   'URL' :      // website
         return  / ( http | ftp | https ) : \/\/ [ \w\-_ ] + ( \. [ \w\-_ ] + ) + ([ \w\- \. ,@?^=%&:/~ \+ # ] * [ \w\- \@ ?^=%&/~ \+ # ]) ? / . test ( str )
       case   'IP' :       //IP
         return  / ((?:(?: 25 [ 0-5 ] | 2 [ 0-4 ] \\ d | [ 01 ] ?\\ d ?\\ d ) \\ . ) {3} (?: 25 [ 0-5 ] | 2 [ 0-4 ] \\ d | [ 01 ] ?\\ d ?\\ d )) / . test ( str );
       case   'date' :     // Date time
         return  / ^ ( \d {4} ) \- ( \d {2} ) \- ( \d {2} )   ( \d {2} )(?: \: \d {2} | : ( \d {2} ) : ( \d {2} )) $ / . test ( str ) ||  / ^ ( \d {4} ) \- ( \d {2} ) \- ( \d {2} ) $ / . test ( str )
       case   'number' :   // Numbers
         return  / ^ [ 0-9 ] $ / . test ( str );
       case   'english' // english
         return  / ^ [ a-zA-Z ] + $ / . test ( str );
       case   'chinese' // chinese
         return  / ^ [ \\ u4E00- \\ u9FA5 ] + $ / . test ( str );
       case   'lower' :    // A lowercase letter
         return  / ^ [ a-z ] + $ / . test ( str );
       case   'upper' :    // Capitalization
         return  / ^ [ A-Z ] + $ / . test ( str );
       case   'HTML' :     //HTML Mark
         return  /< ( " [^ " ] * " | ' [^ ' ] * ' | [^ '"> ]) * >/ . test ( str );
       default :
         return   true ;
    }
  }
 
   //38. Strict ID card verification
   static   isCardID  = ( sId =>  {
     if  (! / ( ^ \d {15} $ ) | ( ^ \d {17} ( \d | X | x ) $ ) / . test ( sId )) {
       console . log ( ' The length or format of your ID card is wrong ' )
       return   false
    }
     // ID card City
     var   aCity  = {  11 :   " Beijing " 12 :   " tianjin " 13 :   " hebei " 14 :   " shanxi " 15 :   " Inner Mongolia " 21 :   " liaoning " 22 :   " Ji Lin " 23 :   " heilongjiang " 31 :   " Shanghai " 32 :   " jiangsu " 33 :   " Zhejiang " 34 :   " anhui " 35 :   " fujian " 36 :   " jiangxi " 37 :   " Shandong " 41 :   " Henan " 42 :   " hubei " 43 :   " hunan " 44 :   " guangdong " 45 :   " guangxi " 46 :   " hainan " 50 :   " Chongqing " 51 :   " sichuan " 52 :   " guizhou " 53 :   " yunnan " 54 :   " Tibet " 61 :   " shaanxi " 62 :   " gansu " 63 :   " qinghai " 64 :   " ningxia " 65 :   " xinjiang " 71 :   " Taiwan " 81 :   " Hong Kong " 82 :   " Macau " 91 :   " Abroad "  };
     if  (! aCity [ parseInt ( sId . substr ( 0 2 ))]) {
       console . log ( ' Your ID card is illegal ' )
       return   false
    }
 
     //  Date of birth verification
     var   sBirthday  = ( sId . substr ( 6 4 ) +  "-"  +  Number ( sId . substr ( 10 2 )) +  "-"  +  Number ( sId . substr ( 12 2 ))). replace ( /-/ g "/" ),
       d  =  new   Date ( sBirthday )
     if  ( sBirthday  != ( d . getFullYear () +  "/"  + ( d . getMonth () +  1 ) +  "/"  +  d . getDate ())) {
       console . log ( ' The date of birth on the ID card is illegal ' )
       return   false
    }
 
     //  ID card number verification
     var   sum  =  0 ,
       weights  = [ 7 9 10 5 8 4 2 1 6 3 7 9 10 5 8 4 2 ],
       codes  =  "10X98765432"
     for  ( var   i  =  0 i  <  sId . length  -  1 i ++) {
       sum  +=  sId [ i ] *  weights [ i ];
    }
     var   last  =  codes [ sum  %  11 ];  // The last ID card number calculated.
     if  ( sId [ sId . length  -  1 ] !=  last ) {
       console . log ( ' The ID number you entered is illegal. ' )
       return   false
    }
 
     return   true
  }
 
   //39. Random number range
   static   random  ( min  =  1 max  =  10 ) {
     if  ( arguments . length  ===  2 ) {
       return   Math . floor ( min  +  Math . random () * (( max  +  1 ) -  min ))
    }  else  {
       return   null ;
    }
  }
 
   //40. Translate Arabic numerals into Chinese capital numerals
   static   numberToChinese  = ( num =>  {
     var   AA  =  new   Array ( " zero " " One " " Two " " 3、 ... and " " Four " " 5、 ... and " " 6、 ... and " " 7、 ... and " " 8、 ... and " " Nine " " Ten " );
     var   BB  =  new   Array ( "" " Ten " " hundred " " Thousand " " Ten thousand " " Billion " " spot " "" );
     var   a  = ( ""  +  num ). replace ( / ( ^ 0 * ) / g "" ). split ( "." ),
       k  =  0 ,
       re  =  "" ;
     for  ( var   i  =  a [ 0 ]. length  -  1 i  >=  0 i --) {
       switch  ( k ) {
         case   0 :
           re  =  BB [ 7 ] +  re ;
           break ;
         case   4 :
           if  (! new   RegExp ( "0{4}//d{"  + ( a [ 0 ]. length  -  i  -  1 ) +  "}$" )
            . test ( a [ 0 ]))
             re  =  BB [ 4 ] +  re ;
           break ;
         case   8 :
           re  =  BB [ 5 ] +  re ;
           BB [ 7 ] =  BB [ 5 ];
           k  =  0 ;
           break ;
      }
       if  ( k  %  4  ==  2  &&  a [ 0 ]. charAt ( i  +  2 ) !=  0  &&  a [ 0 ]. charAt ( i  +  1 ) ==  0 )
         re  =  AA [ 0 ] +  re ;
       if  ( a [ 0 ]. charAt ( i ) !=  0 )
         re  =  AA [ a [ 0 ]. charAt ( i )] +  BB [ k  %  4 ] +  re ;
       k ++;
    }
 
     if  ( a . length  >  1 //  Add the decimal part ( If there is a decimal part )
    {
       re  +=  BB [ 6 ];
       for  ( var   i  =  0 i  <  a [ 1 ]. length i ++)
         re  +=  AA [ a [ 1 ]. charAt ( i )];
    }
     if  ( re  ==  ' Ten ' )
       re  =  " Ten " ;
     if  ( re . match ( / ^ One / ) &&  re . length  ==  3 )
       re  =  re . replace ( " One " "" );
     return   re ;
  }
 
   //41. Convert a number to an amount in words
   static   changeToChinese  = ( Num =>  {
     // To determine if the passed in is not a character, convert it to a character
     if  ( typeof   Num  ==  "number" ) {
       Num  =  new   String ( Num );
    };
     Num  =  Num . replace ( /,/ g "" // Replace tomoney() Medium “,”
     Num  =  Num . replace ( / / g "" // Replace tomoney() Spaces in
     Num  =  Num . replace ( /¥/ g "" // Replace the ones that may appear ¥ character
     if  ( isNaN ( Num )) {  // Verify that the character entered is a number
       //alert(" Please check whether the amount in figures is correct ");
       return   "" ;
    };
     // Character conversion starts after character processing , The former and the latter two parts are converted respectively
     var   part  =  String ( Num ). split ( "." );
     var   newchar  =  "" ;
     // Conversion before decimal point
     for  ( var   i  =  part [ 0 ]. length  -  1 i  >=  0 i --) {
       if  ( part [ 0 ]. length  >  10 ) {
         return   "" ;
         // If the quantity exceeds one billion units , Tips
      }
       var   tmpnewchar  =  ""
       var   perchar  =  part [ 0 ]. charAt ( i );
       switch  ( perchar ) {
         case   "0" :
           tmpnewchar  =  " zero "  +  tmpnewchar ;
           break ;
         case   "1" :
           tmpnewchar  =  " one "  +  tmpnewchar ;
           break ;
         case   "2" :
           tmpnewchar  =  " Ii. "  +  tmpnewchar ;
           break ;
         case   "3" :
           tmpnewchar  =  " 3 "  +  tmpnewchar ;
           break ;
         case   "4" :
           tmpnewchar  =  " boss "  +  tmpnewchar ;
           break ;
         case   "5" :
           tmpnewchar  =  " wu "  +  tmpnewchar ;
           break ;
         case   "6" :
           tmpnewchar  =  " lu "  +  tmpnewchar ;
           break ;
         case   "7" :
           tmpnewchar  =  " Retailer, "  +  tmpnewchar ;
           break ;
         case   "8" :
           tmpnewchar  =  " "  +  tmpnewchar ;
           break ;
         case   "9" :
           tmpnewchar  =  " nine "  +  tmpnewchar ;
           break ;
      }
       switch  ( part [ 0 ]. length  -  i  -  1 ) {
         case   0 :
           tmpnewchar  =  tmpnewchar  +  " element " ;
           break ;
         case   1 :
           if  ( perchar  !=  0 tmpnewchar  =  tmpnewchar  +  " Ten " ;
           break ;
         case   2 :
           if  ( perchar  !=  0 tmpnewchar  =  tmpnewchar  +  " Bai " ;
           break ;
         case   3 :
           if  ( perchar  !=  0 tmpnewchar  =  tmpnewchar  +  " Thousand " ;
           break ;
         case   4 :
           tmpnewchar  =  tmpnewchar  +  " ten thousand " ;
           break ;
         case   5 :
           if  ( perchar  !=  0 tmpnewchar  =  tmpnewchar  +  " Ten " ;
           break ;
         case   6 :
           if  ( perchar  !=  0 tmpnewchar  =  tmpnewchar  +  " Bai " ;
           break ;
         case   7 :
           if  ( perchar  !=  0 tmpnewchar  =  tmpnewchar  +  " Thousand " ;
           break ;
         case   8 :
           tmpnewchar  =  tmpnewchar  +  " Billion " ;
           break ;
         case   9 :
           tmpnewchar  =  tmpnewchar  +  " Ten " ;
           break ;
      }
       var   newchar  =  tmpnewchar  +  newchar ;
    }
     // After the decimal point conversion
     if  ( Num . indexOf ( "." ) != - 1 ) {
       if  ( part [ 1 ]. length  >  2 ) {
         // alert(" Only two digits can be retained after the decimal point , The system will cut off automatically ");
         part [ 1 ] =  part [ 1 ]. substr ( 0 2 )
      }
       for  ( i  =  0 i  <  part [ 1 ]. length i ++) {
         tmpnewchar  =  ""
         perchar  =  part [ 1 ]. charAt ( i )
         switch  ( perchar ) {
           case   "0" :
             tmpnewchar  =  " zero "  +  tmpnewchar ;
             break ;
           case   "1" :
             tmpnewchar  =  " one "  +  tmpnewchar ;
             break ;
           case   "2" :
             tmpnewchar  =  " Ii. "  +  tmpnewchar ;
             break ;
           case   "3" :
             tmpnewchar  =  " 3 "  +  tmpnewchar ;
             break ;
           case   "4" :
             tmpnewchar  =  " boss "  +  tmpnewchar ;
             break ;
           case   "5" :
             tmpnewchar  =  " wu "  +  tmpnewchar ;
             break ;
           case   "6" :
             tmpnewchar  =  " lu "  +  tmpnewchar ;
             break ;
           case   "7" :
             tmpnewchar  =  " Retailer, "  +  tmpnewchar ;
             break ;
           case   "8" :
             tmpnewchar  =  " "  +  tmpnewchar ;
             break ;
           case   "9" :
             tmpnewchar  =  " nine "  +  tmpnewchar ;
             break ;
        }
         if  ( i  ==  0 tmpnewchar  =  tmpnewchar  +  " horn " ;
         if  ( i  ==  1 tmpnewchar  =  tmpnewchar  +  " branch " ;
         newchar  =  newchar  +  tmpnewchar ;
      }
    }
     // Replace all useless Chinese characters
     while  ( newchar . search ( " zero zero " ) != - 1 )
       newchar  =  newchar . replace ( " zero zero " " zero " );
     newchar  =  newchar . replace ( " zero " " Billion " );
     newchar  =  newchar . replace ( " One hundred million " " Billion " );
     newchar  =  newchar . replace ( " zero " " ten thousand " );
     newchar  =  newchar . replace ( " zero yuan " " element " );
     newchar  =  newchar . replace ( " Zero angle " "" );
     newchar  =  newchar . replace ( " Zero point " "" );
     if  ( newchar . charAt ( newchar . length  -  1 ) ==  " element " ) {
       newchar  =  newchar  +  " whole "
    }
     return   newchar ;
  }
 
   //42. Determine whether an element is in an array
   static   contains  = ( arr val =>  {
     return   arr . indexOf ( val ) != - 1  ?  true  :  false ;
  }
 
   //43. Array sorting ,{type} 1: From small to large  2: From big to small  3: Random
   static   sort  = ( arr type  =  1 =>  {
     return   arr . sort (( a b =>  {
       switch  ( type ) {
         case   1 :
           return   a  -  b ;
         case   2 :
           return   b  -  a ;
         case   3 :
           return   Math . random () -  0.5 ;
         default :
           return   arr ;
      }
    })
  }
 
   //44. duplicate removal
   static   unique  = ( arr =>  {
     if  ( Array . hasOwnProperty ( 'from' )) {
       return   Array . from ( new   Set ( arr ));
    }  else  {
       var   n  = {},  r  = [];
       for  ( var   i  =  0 i  <  arr . length i ++) {
         if  (! n [ arr [ i ]]) {
           n [ arr [ i ]] =  true ;
           r . push ( arr [ i ]);
        }
      }
       return   r ;
    }
  }
 
   //45. Find the union of two sets
   static   union  = ( a b =>  {
     var   newArr  =  a . concat ( b );
     return   this . unique ( newArr );
  }
 
   //46. Find the intersection of two sets
   static   intersect  = ( a b =>  {
     var   _this  =  this ;
     a  =  this . unique ( a );
     return   this . map ( a function  ( o ) {
       return   _this . contains ( b o ) ?  o  :  null ;
    });
  }
 
   //47. Delete one of the elements
   static   remove  = ( arr ele =>  {
     var   index  =  arr . indexOf ( ele );
     if  ( index  > - 1 ) {
       arr . splice ( index 1 );
    }
     return   arr ;
  }
 
   //48. Convert a class array to an array
   static   formArray  = ( ary =>  {
     var   arr  = [];
     if  ( Array . isArray ( ary )) {
       arr  =  ary ;
    }  else  {
       arr  =  Array . prototype . slice . call ( ary );
    };
     return   arr ;
  }
 
   //49. Maximum
   static   max  = ( arr =>  {
     return   Math . max . apply ( null arr );
  }
 
   //50. minimum value
   static   min  = ( arr =>  {
     return   Math . min . apply ( null arr );
  }
 
   //51. Sum up
   static   sum  = ( arr =>  {
     return   arr . reduce (( pre cur =>  {
       return   pre  +  cur
    })
  }
 
   //52. Average
   static   average  = ( arr =>  {
     return   this . sum ( arr ) /  arr . length
  }
 
   //53. Remove the space ,type: 1- All spaces  2- Space before and after  3- Front space  4- Space after
   static   trim  = ( str type =>  {
     type  =  type  ||  1
     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 ;
    }
  }
 
   //54. Character conversion ,type: 1: title case  2: Initial lowercase  3: toggle case  4: All capitals  5: All lowercase
   static   changeCase  = ( str type =>  {
     type  =  type  ||  4
     switch  ( type ) {
       case   1 :
         return   str . replace ( / \b \w + \b / g function  ( word ) {
           return   word . substring ( 0 1 ). toUpperCase () +  word . substring ( 1 ). toLowerCase ();
 
        });
       case   2 :
         return   str . replace ( / \b \w + \b / g function  ( word ) {
           return   word . substring ( 0 1 ). toLowerCase () +  word . substring ( 1 ). toUpperCase ();
        });
       case   3 :
         return   str . split ( '' ). map ( function  ( word ) {
           if  ( / [ a-z ] / . test ( word )) {
             return   word . toUpperCase ();
          }  else  {
             return   word . toLowerCase ()
          }
        }). join ( '' )
       case   4 :
         return   str . toUpperCase ();
       case   5 :
         return   str . toLowerCase ();
       default :
         return   str ;
    }
  }
 
   //55. Detect password strength
   static   checkPwd  = ( str =>  {
     var   Lv  =  0 ;
     if  ( str . length  <  6 ) {
       return   Lv
    }
     if  ( / [ 0-9 ] / . test ( str )) {
       Lv ++
    }
     if  ( / [ a-z ] / . test ( str )) {
       Lv ++
    }
     if  ( / [ A-Z ] / . test ( str )) {
       Lv ++
    }
     if  ( / [ \. |-|_ ] / . test ( str )) {
       Lv ++
    }
     return   Lv ;
  }
 
   //56. Function restrictor
   static   debouncer  = ( fn time interval  =  200 =>  {
     if  ( time  - ( window . debounceTimestamp  ||  0 ) >  interval ) {
       fn  &&  fn ();
       window . debounceTimestamp  =  time ;
    }
  }
 
   //57. Insert a new string into a string
   static   insertStr  = ( soure index newStr =>  {
     var   str  =  soure . slice ( 0 index ) +  newStr  +  soure . slice ( index );
     return   str ;
  }
 
   //58. Determine whether two objects have the same key value
   static   isObjectEqual  = ( a b =>  {
     var   aProps  =  Object . getOwnPropertyNames ( a );
     var   bProps  =  Object . getOwnPropertyNames ( b );
 
     if  ( aProps . length  !==  bProps . length ) {
       return   false ;
    }
 
     for  ( var   i  =  0 i  <  aProps . length i ++) {
       var   propName  =  aProps [ i ];
 
       if  ( a [ propName ] !==  b [ propName ]) {
         return   false ;
      }
    }
     return   true ;
  }
 
   //59.16 Base color conversion RGBRGBA character string
   static   colorToRGB  = ( val opa =>  {
 
     var   pattern  =  / ^ ( # ? )[ a-fA-F0-9 ] {6} $ / //16 Color value check rule
     var   isOpa  =  typeof   opa  ==  'number' // Determine whether the opacity is set
 
     if  (! pattern . test ( val )) {  // If the value does not conform to the rule, the null character is returned
       return   '' ;
    }
 
     var   v  =  val . replace ( /#/ '' );  // If there is # The number is removed first # Number
     var   rgbArr  = [];
     var   rgbStr  =  '' ;
 
     for  ( var   i  =  0 i  <  3 i ++) {
       var   item  =  v . substring ( i  *  2 i  *  2  +  2 );
       var   num  =  parseInt ( item 16 );
       rgbArr . push ( num );
    }
 
     rgbStr  =  rgbArr . join ();
     rgbStr  =  'rgb'  + ( isOpa  ?  'a'  :  '' ) +  '('  +  rgbStr  + ( isOpa  ?  ','  +  opa  :  '' ) +  ')' ;
     return   rgbStr ;
  }
 
   //60. Additional url Parameters
   static   appendQuery  = ( url key value =>  {
     var   options  =  key ;
     if  ( typeof   options  ==  'string' ) {
       options  = {};
       options [ key ] =  value ;
    }
     options  =  $ . param ( options );
     if  ( url . includes ( '?' )) {
       url  +=  '&'  +  options
    }  else  {
       url  +=  '?'  +  options
    }
     return   url ;
  }
 
   /**
 *  Intercepts the string of the specified byte
 *  @param   str   The characters to be intercepted wear
 *  @param   len   The length to be cut , Based on bytes
 *  @param   suffix   Before interception len After a , Replacement characters for the rest of the characters , It's usually used “…”
 *  @returns   {*}
 */
 
   static   cutString  ( str len suffix ) {
     if  (! str return   "" ;
     if  ( len  <=  0 return   "" ;
     if  (! suffix suffix  =  "" ;
     var   templen  =  0 ;
     for  ( var   i  =  0 i  <  str . length i ++) {
       if  ( str . charCodeAt ( i ) >  255 ) {
         templen  +=  2 ;
      }  else  {
         templen ++
      }
       if  ( templen  ==  len ) {
         return   str . substring ( 0 i  +  1 ) +  suffix ;
      }  else   if  ( templen  >  len ) {
         return   str . substring ( 0 i ) +  suffix ;
      }
    }
     return   str ;
  }
 
   /**
 *  Object cloning & Deep copy
 *  @method   cloneObj
 *  @param   obj
 *  @returns   {{}}
 */
   static   cloneObj  ( obj ) {
     var   newO  = {};
     if  ( obj   instanceof   Array ) {
       newO  = [];
    }
     for  ( var   key   in   obj ) {
       var   val  =  obj [ key ];
       newO [ key ] =  typeof   val  ===  'object'  ?  arguments . callee ( val ) :  val ;
    }
     return   newO ;
  };
 
   /**
 *  Object cloning & Deep copy
 *  @method   clone
 *  @param   obj
 *  @returns   {{}}
 */
   static   clone  ( obj ) {
     // Handle the 3 simple types, and null or undefined
     if  ( null  ==  obj  ||  "object"  !=  typeof   obj return   obj ;
 
     // Handle Date
     if  ( obj   instanceof   Date ) {
       var   copy  =  new   Date ();
       copy . setTime ( obj . getTime ());
       return   copy ;
    }
 
     // Handle Array
     if  ( obj   instanceof   Array ) {
       var   copy  = [];
       for  ( var   i  =  0 len  =  obj . length i  <  len ; ++ i ) {
         copy [ i ] =  clone ( obj [ i ]);
      }
       return   copy ;
    }
 
     // Handle Object
     if  ( obj   instanceof   Object ) {
       var   copy  = {};
       for  ( attr   in   obj ) {
         if  ( obj . hasOwnProperty ( attr ))  copy [ attr ] =  clone ( obj [ attr ]);
      }
       return   copy ;
    }
 
     throw   new   Error ( "Unable to copy obj! Its type isn't supported." );
  }
 
   static   setHtmlRem  () {
     var   rem  = {
       baseRem :   40 //  Reference size , according to iphone6 Should be 20, Expand here 2 times , Easy to calculate
       baseWidth :   750 //  Base dimension width , Here is according to ihpone6 The size of the
       rootEle :   document . getElementsByTagName ( "html" )[ 0 ],
       initHandle :   function  () {
         this . setRemHandle ();
         this . resizeHandle ();
      },
       setRemHandle :   function  () {
         var   clientWidth  =  document . documentElement . clientWidth  ||  document . body . clientWidth ;
         this . rootEle . style . fontSize  =  clientWidth  *  this . baseRem  /  this . baseWidth  +  "px" ;
      },
       resizeHandle :   function  () {
         var   that  =  this ;
         window . addEventListener ( "resize" function  () {
           setTimeout ( function  () {
             that . setRemHandle ();
          },  300 );
        });
      }
    };
     rem . initHandle ();
  }
 
   //17. Generate random color values
   static    getRandomColor  () {
     const   rgb  = []
     for  ( let   i  =  0  ;  i  <  3 ; ++ i ){
       let   color  =  Math . floor ( Math . random () *  256 ). toString ( 16 );
       color  =  color . length  ==  1  ?  '0'  +  color  :  color ;
       rgb . push ( color );
    }
     return   '#'  +  rgb . join ( '' );
  }
}

版权声明
本文为[Calligraphy and sword in the world]所创,转载请带上原文链接,感谢
https://cdmana.com/2020/12/20201224172417493h.html

Scroll to Top