JS 工具类

之前工作用的JavaScript比较多,总结了一下工具类,和大家分享一下,有不足之处还请多多见谅!!

  1 1. 数组工具类(arrayUtils)
  2 var arrayUtils = {};
  3 (function (object) {
  4     //arguments parameter
  5     object.concat = function (arr) {
  6         if (arguments.length > 0) {
  7             for (i = 1;i < arguments.length; i++) {
  8                 arr=arr.concat(arguments[i]);
  9             }
 10         }
 11         return arr;
 12     };
 13     object.join = function (arr,separator) {
 14         return arr.join(separator);
 15     };
 16     object.push = function (arr) {
 17         if (arguments.length > 0) {
 18             for (i = 1;i < arguments.length; i++) {
 19                 arr.push(arguments[i]);
 20             }
 21         }
 22         return arr;
 23     };
 24     object.slice = function (arr,start,end) {
 25         return arr.slice(start,end);
 26     };
 27     object.sort = function (arr,isDesc) {
 28          if(isDesc){
 29              arr.sort(function (a,b) {
 30                  return a<b?1:-1;
 31              });
 32          }else{
 33              arr.sort(function (a,b) {
 34                  return a<b?-1:1;
 35              });
 36          }
 37          return arr;
 38     };
 39     object.unshift = function (arr) {
 40         if (arguments.length > 0) {
 41             for (i = 1;i < arguments.length; i++) {
 42                 arr.unshift(arguments[i]);
 43             }
 44         }
 45         return arr;
 46     };
 47     object.inArray=function (arr,targetValue) {
 48         var hasTargetValue=false;
 49         $.each(arr,function (index,item) {
 50             if(item==targetValue){
 51                 hasTargetValue=true;
 52             }
 53         });
 54         return hasTargetValue;
 55     };
 56     //差集
 57     object.except=function (sourceArray,targetArray) {
 58         var self=this;
 59         var exceptArray=[];
 60         $.each(sourceArray,function (index,item) {
 61             if(!self.inArray(targetArray,item)){
 62                 exceptArray.push(item);
 63             }
 64         });
 65         $.each(targetArray,function (index,item) {
 66             if(!self.inArray(sourceArray,item)){
 67                 exceptArray.push(item);
 68             }
 69         });
 70         return exceptArray;
 71     };
 72     //交集
 73     object.intersect=function (sourceArray,targetArray) {
 74         var self=this;
 75         var intersectArray=[];
 76         $.each(sourceArray,function (index,item) {
 77             if(self.inArray(targetArray,item)){
 78                 intersectArray.push(item);
 79             }
 80         });   
 81         return intersectArray;
 82     };
 83 })(arrayUtils);
 84 
 85 2.Cookie工具类(cookieUtils)
 86 var cookieUtils={};
 87 (function (object) {
 88      object.setCookie=function (key,value,expires) {
 89          $.cookie(key, JSON.stringify(data), { expires: expires, path: '/' });
 90      };
 91      object.getCookie=function (key) {
 92          return $.cookie(key);
 93      };
 94     object.getServerCookie=function (cookieName,key) {
 95         var cookieValue = $.cookie(cookieName);
 96         var cookieItems = cookieValue.split('&');
 97         var itemValue = '';
 98         $.each(cookieItems, function (index, item) {
 99             if (item.indexOf(key) > -1) {
100                 itemValue = item.match(/=.*/g)[0].replace(/=/, '');
101             }
102         });
103         return itemValue;
104     };
105      object.clearCookie=function (key,expires) {
106          $.cookie(key, null, { expires: expires, path: '/' });
107      };
108 })(cookieUtils);
109 
110 3.日期工具类(dateTimeUtils)
111 /**
112  * Created by JerryChen on 2016/12/30.
113  */
114 var dateTimeUtils = {};
115 (function (object) {
116     object.now = function () {
117         return new Date();
118     };
119     object.toString = function (value, format) {
120         var returnValue = '';
121         var placeHolder = '00';
122         var separator = '';
123         var formatArray = ['y', 'M', 'd', 'h', 'm', 's'];
124         var yearFormat = format.match(/y+/g);
125         var formatLength = 0;
126         var isContains = false;
127         if (yearFormat != null && yearFormat[0].length <= 4) {
128             formatLength += yearFormat[0].length;
129             var yearValue = value.getFullYear().toString();
130             separator = format.substr(formatLength, 1);
131             isContains = inArray(formatArray, separator);
132             if (isContains) {
133                 separator = "";
134             } else {
135                 formatLength += 1;
136             }
137             returnValue += yearValue.substr(4 - yearFormat[0].length, yearFormat[0].length) + separator;
138         }
139         var monthFormat = format.match(/M+/g);
140         if (monthFormat != null && monthFormat[0].length <= 2) {
141             formatLength += monthFormat[0].length;
142             var monthValue = (value.getMonth() + 1).toString();
143             separator = format.substr(formatLength, 1);
144             isContains = inArray(formatArray, separator);
145             if (isContains) {
146                 separator = "";
147             } else {
148                 formatLength += 1;
149             }
150             returnValue += placeHolder.substr(0, 2 - monthFormat[0].length) + monthValue + separator;
151         }
152         var dayFormat = format.match(/d+/g);
153         if (dayFormat != null && dayFormat[0].length <= 2) {
154             formatLength += dayFormat[0].length;
155             var dayValue = value.getDate().toString();
156             separator = format.substr(formatLength, 1);
157             isContains = inArray(formatArray, separator);
158             if (isContains) {
159                 separator = " ";
160             } else {
161                 formatLength += 1;
162             }
163             returnValue += placeHolder.substr(0, 2 - dayFormat[0].length) + dayValue + separator;
164         }
165         var hourFormat = format.match(/h+/g);
166         if (hourFormat != null && hourFormat[0].length <= 2) {
167             formatLength += hourFormat[0].length;
168             var hourValue = value.getHours().toString();
169             separator = format.substr(formatLength, 1);
170             isContains = inArray(formatArray, separator);
171             if (isContains) {
172                 separator = "";
173             } else {
174                 formatLength += 1;
175             }
176             returnValue += placeHolder.substr(0, 2 - hourFormat[0].length) + hourValue + separator;
177         }
178         var minutesFormat = format.match(/m+/g);
179         if (minutesFormat != null && minutesFormat[0].length <= 2) {
180             formatLength += minutesFormat[0].length;
181             var minutesValue = value.getMinutes().toString();
182             separator = format.substr(formatLength, 1);
183             isContains = inArray(formatArray, separator);
184             if (isContains) {
185                 separator = "";
186             } else {
187                 formatLength += 1;
188             }
189             returnValue += placeHolder.substr(0, 2 - minutesFormat[0].length) + minutesValue + separator;
190         }
191         secondsFormat = format.match(/s+/g);
192         if (secondsFormat != null && secondsFormat[0].length <= 2) {
193             var secondsValue = value.getSeconds();
194             returnValue += placeHolder.substr(0, 2 - secondsFormat[0].length) + secondsValue;
195         }
196         return returnValue;
197     };
198     function inArray(array, targetValue) {
199         var flag = false;
200         $.each(array, function (index, item) {
201             if (targetValue == item) {
202                 flag = true;
203             }
204         });
205         return flag;
206     }
207     object.dateDiff = function (startDate, endDate, format) {
208         if (format == "dd") {
209            return (endDate.getTime()-startDate.getTime())/86400000;
210         } else if (format == "hh") {
211             return Math.ceil((endDate.getTime()-startDate.getTime())/3600000);
212         } else if (format == "mm") {
213             return Math.ceil((endDate.getTime()-startDate.getTime())/60000);
214         } else if (format == "ss") {
215             return Math.ceil((endDate.getTime()-startDate.getTime())/1000);
216         }
217     };
218     object.addDays = function (value, days) {
219         return new Date(value.getTime() + days * 86400000);
220     };
221     object.addHours = function (value, hours) {
222         return new Date(value.getTime() + hours * 3600000);
223     };
224     object.addMinutes = function (value, minutes) {
225         return new Date(value.getTime() + minutes * 60000);
226     };
227     object.addSeconds = function (value, seconds) {
228         return new Date(value.getTime() + seconds * 1000);
229     };
230 })(dateTimeUtils);
231 
232 4.枚举工具类(enumUtils)
233 /**
234  * Created by JerryChen on 2016/12/31.
235  */
236 var enumUtils={};
237 (function (object) {
238     object.getEnumValue=function (enumSource,key) {
239        return enumSource[key];
240     };
241     object.getEnumData=function (enumSource) {
242         var data=[];
243        for (item in enumSource){
244            data.push({"Key":item,"Value":enumSource[item]})
245        }
246        return data;
247     };
248 
249 })(enumUtils);
250 
251 5.Json工具类(jsonUtils)
252 /**
253  * Created by JerryChen on 2016/12/31.
254  */
255 var jsonUtils={};
256 (function (object) {
257     object.grepJsonArray=function (dataSource,filterRule) {
258         //var defaultRule=[{"FilterField":"","Value":"","Operator":""}];
259         if(filterRule!=undefined&&filterRule!=null&&filterRule.length>0){
260             $.each(filterRule,function (index,item) {
261                 if (item.Operator=="="){
262                     dataSource= $.grep(dataSource, function (item, index) {
263                         return item.FilterField == item.Value;
264                     }, false);
265                 }
266                 if (item.Operator=="!="){
267                     dataSource= $.grep(dataSource, function (item, index) {
268                         return item.FilterField != item.Value;
269                     }, false);
270                 }
271             });
272         }
273         return dataSource;
274     };
275     /**
276      * @return {boolean}
277      */
278     object.isNotNullOrEmpty=function (dataSource) {
279         return dataSource!=undefined&&dataSource!=null&&dataSource.length>0;
280 
281     };
282     object.isNotEmptyObject=function (dataSource) {
283         return !$.isEmptyObject(dataSource);
284     };
285     object.getObjectProperty=function (dataSource,propertyName) {
286         return dataSource[propertyName];
287     };
288     object.removeObjectProperty=function (dataSource,propertyName) {
289         delete dataSource[propertyName];
290         return dataSource;
291     }
292 
293 })(jsonUtils);
294 
295 6.Mapper工具类(mapperUtils)
296 /**
297  * Created by JerryChen on 2016/12/31.
298  */
299 var mapperUtils={};
300 (function (object) {
301     object.extend=function (dataSource,dataTarget) {
302         $.extend(true,dataTarget,dataSource);
303         return dataTarget;
304     };
305 })(mapperUtils);
306 
307 7.Number工具类(numberUtils)
308 /**
309  * Created by JerryChen on 2016/12/30.
310  */
311 var numberUtils = {};
312 (function (object) {
313     object.isNumber = function (value) {
314         if (/\d+/.test(value)) {
315             return true;
316         }
317         return false;
318     };
319     object.toInt = function (value) {
320         if (this.isNumber(value)) {
321             return parseInt(value);
322         } else {
323             return value;
324         }
325     };
326     object.toDouble = function (value, number) {
327         return value.toFixed(number);
328     };
329     object.toFloat = function (value) {
330         return parseFloat(value);
331     };
332     object.max = function () {
333         var maxValue;
334         if (arguments.length > 0) {
335             if (arguments.length == 1) {
336                 arguments[0].sort(function (a, b) {
337                     return a > b ? -1 : 1;
338                 });
339                 maxValue = arguments[0][0];
340             } else {
341                 var arr=[];
342                for(i=0;i<arguments.length;i++){
343                    arr.push(arguments[i]);
344                }
345                 arr.sort(function (a, b) {
346                     return a > b ? -1 : 1;
347                 });
348                 maxValue = arr[0];
349             }
350         }
351         return maxValue;
352     };
353     object.min = function () {
354         var minValue;
355         if (arguments.length > 0) {
356             if (arguments.length == 1) {
357                 arguments[0].sort(function (a, b) {
358                     return a > b ? 1 : -1;
359                 });
360                 minValue = arguments[0][0];
361             } else {
362                 var arr=[];
363                 for(i=0;i<arguments.length;i++){
364                     arr.push(arguments[0]);
365                 }
366                 arr.sort(function (a, b) {
367                     return a > b ? 1 : -1;
368                 });
369                 maxValue = arr[0];
370             }
371         }
372         return minValue;
373     }
374 })(numberUtils);
375 
376 8.String工具类(stringUtils)
377 /**
378  * Created by JerryChen on 2016/12/30.
379  */
380 var stringUtils={};
381 (function (object) {
382     object.subString=function (value,start,length) {
383         return value.substr(start,length);
384     };
385     object.truncate=function (value,maxLength,suffix) {
386         if(value!=undefined&&value.length>maxLength){
387            value=value.substr(0,maxLength)+suffix;
388         }
389         return value;
390     };
391     object.length=function (value) {
392         if(value!=undefined){
393             return value.length;
394         }else {
395             return 0;
396         }
397     };
398     object.endTrim=function (value) {
399         if(value!=undefined){
400             value=value.substr(0,value.length-1);
401         }
402         return value;
403     };
404     object.isNotNull=function (value) {
405         return value!=undefined&&value!=null;
406     };
407     object.isNotNullOrEmpty=function (value) {
408         return value!=undefined&&value!=null&&value!="";
409     };
410     object.isEqual=function (value,compareWith) {
411         return value==compareWith;
412     };
413     object.indexOf=function (value,targetValue) {
414         return value.indexOf(targetValue);
415     }
416 })(stringUtils);
417 
418 
419 
420 
421 
422 
423 9.Url工具类(urlUtils)
424 /**
425  * Created by JerryChen on 2016/12/31.
426  */
427 var urlUtils={};
428 (function (object) {
429     object.getParam= function (search,paramName) {
430         var reg = new RegExp("(^|&)" + paramName + "=([^&]*)(&|$)");
431         var result = search.substr(1).match(reg);
432         if (result != null) {
433             return decodeURIComponent(result[2]);
434         } else {
435             return undefined;
436         }
437     };
438     object.getHost=function () {
439         return window.location.host;
440     }
441 })(urlUtils);
442 
443 10.StringBuilder
444 function StringBuilder() {
445     this._string = new Array();
446 };
447 StringBuilder.prototype.append = function (str) {
448     this._string.push(str);
449     return this;
450 };
451 StringBuilder.prototype.appendLine = function (str) {
452     this._string.push(str + "\n");
453     return this;
454 };
455 StringBuilder.prototype.appendFormat = function (value) {
456     for (var i = 1; i < arguments.length; i++) {
457         var placeHolder = "\\{" + (i - 1) + "\\}";
458         var reg = new RegExp(placeHolder, "g");
459         value = value.replace(reg, arguments[i]);
460     }
461     this._string.push(value);
462     return this;
463 };
464 StringBuilder.prototype.toString = function () {
465     return this._string.join("");
466 }

 

 

github地址:https://github.com/jerrychen0705/JS.Utilities

 

posted @ 2017-01-04 17:13  JerryChen89  阅读(566)  评论(0)    收藏  举报