Skip to content

Instantly share code, notes, and snippets.

@dead-horse
Created June 21, 2012 08:22
Show Gist options
  • Save dead-horse/2964560 to your computer and use it in GitHub Desktop.
Save dead-horse/2964560 to your computer and use it in GitHub Desktop.
front end utils
/**
* 复制对象、数组
* @param {Object} obj [原始对象]
* @return {Object} [复制的对象]
*/
function clone(obj){
var objClone;
if (obj.constructor == Object){
objClone = new obj.constructor();
}else{
objClone = [];
}
for(var key in obj){
if ( objClone[key] != obj[key] ){
if ( typeof(obj[key]) == 'object' ){
objClone[key] = clone(obj[key]);
}else{
objClone[key] = obj[key];
}
}
}
return objClone;
}
/**
* 模版替换
* @param {String} tpl [模版, 中间的$tpl$是要被替换的]
* @param {Object} params [要替换的键值对]
* @return {String}
*/
function tplReplace(tpl, params){
return tpl.replace(/\$.*?\$/g, function(data){
return params[data];
});
}
/**
* 转换html特殊字符
* @param {String} res
* @return {String}
*/
function htmlEncode(res){
return res.replace(/&/g, '&').
replace(/</g, '&lt;').
replace(/>/g, '&gt;').
replace(/'/g, '&acute;').
res.replace(/"/g, '&quot;').
res.replace(/\|/g, '&brvbar;');
}
/**
* 格式化日期显示,类似新浪微博的10秒前,1分钟前
* @param {Date} date [要转换的日期]
* @param {Bool} friendly [是否转化成显示友好的(e.x:10秒前)]
* @param {Date} now [系统标准时间]
* @param {Int} deepth [深度,默认到分钟级别]
* @return {String}
*/
function dateFormat(date, friendly, now, deepth) {
deepth = deepth || 2;
var year = date.getFullYear();
var month = date.getMonth() + 1;
var day = date.getDate();
var hour = date.getHours();
var minute = date.getMinutes();
var second = date.getSeconds();
if (friendly && now && now.getTime() >= date.getTime()) {
var mseconds = now.getTime() - date.getTime();
var time_std = [ 1000, 60 * 1000, 60 * 60 * 1000, 24 * 60 * 60 * 1000 ];
var display = ['秒前', '分钟前', '小时前'];
for (var i=0; i!=deepth; ++i) {
if (mseconds < time_std[i + 1]) {
return Math.floor(mseconds / time_std[i]) + display[i];
}
}
}
hour = ((hour < 10) ? '0' : '') + hour;
minute = ((minute < 10) ? '0' : '') + minute;
second = ((second < 10) ? '0': '') + second;
return year + '-' + month + '-' + day + ' ' + hour + ':' + minute;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment