JSUtil.js 2.37 KB
/**
 * JSUtil General JS scripting tools
 */
( function( window ) {
	var noop=function(){};
	var log=function(msg){
		if ( window.console ) {
			console.log(msg);
		}
	}
	var recursion=function(items,options){
		var config={
			'isRoot':function(item){
				return !item['parentId'];
			},
			'isChild':function(itemA,itemB){
				return itemA['id']==itemB['parentId'];	
			},
			'generateResult':function(item,children){
				item['children']=children;
				return item;
			}
		};
		jQuery.extend(config, options);
		var innerFN=function(item,items){
			var children=[];
			for(var i=0;i<items.length;i++){
				if(config.isChild(item,items[i])){
					var temp=innerFN(items[i],items);
					if(temp){
						children.push(temp);	
					}
				}	
			}
			return config.generateResult(item,children);
		}
		var results=[];
		for(var i=0;i<items.length;i++){
			if(config.isRoot(items[i])){
				var result=innerFN(items[i],items);
				if(result){
					results.push(result);
				}
			}
		}
		return results;
	}
	var strfmt=function(str){
		if(!str)return null;
		for(var i=1;i<arguments.length;i++){
			str = str.replace(new RegExp("\\{" + i + "\\}", "g"), arguments[i]);
		}
		return str;
	}
	var uuid=function(delSeparator) {
		var s = [];
		var hexDigits = "0123456789abcdef";
		for (var i = 0; i < 36; i++) {
			s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
		}
		s[14] = "4";
		s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);
		if(delSeparator){
			s[8] = s[13] = s[18] = s[23] = "";
		}else{
			s[8] = s[13] = s[18] = s[23] = "-";
		}
		var uuid = s.join("");
		return uuid;
	}
	var formatSize=function( size, pointLength, units ) {
		var unit;
		units = units || [ 'B', 'K', 'M', 'G', 'TB' ];
		while ( (unit = units.shift()) && size > 1024 ) {
			size = size / 1024;
		}
		return (unit === 'B' ? size : size.toFixed( pointLength || 2 )) + unit;
	}
	var get=function(){
		$.ajaxSetup({async:false})
		$.get.apply(this,arguments);
		$.ajaxSetup({async:true})
	}
	var post=function(){
		$.ajaxSetup({async:false})
		$.post.apply(this,arguments);
		$.ajaxSetup({async:true})
	}
	var getJSON=function(){
		$.ajaxSetup({async:false})
		$.getJSON.apply(this,arguments);
		$.ajaxSetup({async:true})
	}
	var JSUtil={
		'noop':noop,
		'log':log,
		'recursion':recursion,
		'strfmt':strfmt,
		'uuid':uuid,
		'formatSize':formatSize,
		'get':get,
		'post':post,
		'getJSON':getJSON,
	};
	window.JSUtil = JSUtil;
} )( window );