Skip to content

Instantly share code, notes, and snippets.

@sursir
Last active September 11, 2015 01:50
Show Gist options
  • Save sursir/43a7a64f0be6555539a7 to your computer and use it in GitHub Desktop.
Save sursir/43a7a64f0be6555539a7 to your computer and use it in GitHub Desktop.
JavaScript
/**
* 返回字符串对象中特殊符号的位置
* 不存在返回 -1
*/
String.prototype.indexOfSymbol = function () {
return this.search(/[^a-zA-Z0-9\u2E80-\u9FFF]+/);
}
function Iterator(start, end)
{
this.range = [];
for (var i = start; i <= end; i++) {
this.range.push(i);
};
console.log(this.range);
this.start = start;
this.end = end;
this.p = 0;
this.value = this.range[this.p];
this.done = false;
}
Iterator.prototype.next = function(){
this.p++;
this.value = this.range[this.p];
if (this.range[this.p] == undefined) {
this.done = true;
}
}
for (var iter = new Iterator(1, 10); !iter.done; iter.next()) {
console.log(iter.value, iter.done);
}
var TemplateEngine = function(html, options) {
    var re = /<%([^%>]+)?%>/g, reExp = /(^( )?(if|for|else|switch|case|break|{|}))(.*)?/g, code = 'var r=[];\n', cursor = 0;
    var add = function(line, js) {
        js? (code += line.match(reExp) ? line + '\n' : 'r.push(' + line + ');\n') :
            (code += line != '' ? 'r.push("' + line.replace(/"/g, '\\"') + '");\n' : '');
        return add;
    }
    while(match = re.exec(html)) {
        add(html.slice(cursor, match.index))(match[1], true);
        cursor = match.index + match[0].length;
    }
    add(html.substr(cursor, html.length - cursor));
    code += 'return r.join("");';
    return new Function(code.replace(/[\r\t\n]/g, '')).apply(options);
}

JavaScript template engine in just 20 lines

#####原文 -> #####Jobbole 译文 ->

var TemplateEngine = function(html, options) {
    var re = /<%([^%>]+)?%>/g, reExp = /(^( )?(if|for|else|switch|case|break|{|}))(.*)?/g, code = 'var r=[];\n', cursor = 0;
    var add = function(line, js) {
        js? (code += line.match(reExp) ? line + '\n' : 'r.push(' + line + ');\n') :
            (code += line != '' ? 'r.push("' + line.replace(/"/g, '\\"') + '");\n' : '');
        return add;
    }
    while(match = re.exec(html)) {
        add(html.slice(cursor, match.index))(match[1], true);
        cursor = match.index + match[0].length;
    }
    add(html.substr(cursor, html.length - cursor));
    code += 'return r.join("");';
    return new Function(code.replace(/[\r\t\n]/g, '')).apply(options);
}

My JavaScript Snippet

/**
* 合并扩展对象方法
* @param {Object|Array} object 要被合并的对象或对象数组
* @param {Boolean} override 相同对象的属性是否要重写
* @return {null} 没有返回值
*/
Object.prototype.extend = function (object, override) {
var that = this;
function ext(object, override){
for (key in object) {
if (object.hasOwnProperty(key)
&& ((! that.hasOwnProperty(key)) || override)) {
that[key] = object[key];
}
}
}
if (object instanceof Array) {
object.map(function(val){
ext(val, override);
});
} else {
ext(object, override);
}
}
function timeString(delay, time){
var reg = /^(\+|-) ?(\d+) ?(day|month|year|hours|minutes|seconds)$/;
var method = [];
var datetime = new Date();
if (typeof time != 'undefined') {
try {
datetime = new Date(time);
} catch (e) {
console.error(e);
return false;
}
}
var localeDate = datetime.toLocaleDateString();
// var datePart = convDate(localeDate, '-');
var year = datetime.getYear() + 1900,
month = datetime.getMonth() + 1,
date = datetime.getDate(),
hours = datetime.getHours(),
minutes = datetime.getMinutes(),
seconds = datetime.getSeconds();
var dateMaps = {
day: date,
month: month,
year: year,
hours: hours,
minutes: minutes,
seconds: seconds
};
var funcMaps = {
day: 'setDate',
month: 'setMonth',
year: 'setYear',
hours: 'setHours',
minutes: 'setMinutes',
seconds: 'setSeconds'
}
var old = 0,
add = 0,
newTime = 0;
if (delay) {
method = delay.match(reg);
add = parseInt(method[2]);
newTime = method[1] == '+' ? dateMaps[method[3]] + add : dateMaps[method[3]] - add;
datetime[funcMaps[method[3]]](newTime);
dateMaps.year = datetime.getYear() + 1900;
dateMaps.month = datetime.getMonth() + 1;
dateMaps.day = datetime.getDate();
dateMaps.hours = datetime.getHours(),
dateMaps.minutes = datetime.getMinutes(),
dateMaps.seconds = datetime.getSeconds();
}
var datePart = [dateMaps.year, dateMaps.month, dateMaps.day].join('-');
var timePart = [dateMaps.hours, dateMaps.minutes, dateMaps.seconds].join(':');
var now = datePart + ' ' + timePart;
return now;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment