发个JS代码缩进格式化

来源:互联网 发布:黑马程序员论坛 编辑:程序博客网 时间:2024/06/03 02:27

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>CFormat</title>
<style type="text/css">
body {
    text-align:center;
    margin-top:10px;
}

textarea, div {
    margin:auto;
    width:900px;
    height:500px;
    line-height:18px;
    font-size:12px;
    text-align:left;
}

* {
    margin:auto;
}
</style>
<script type="text/javascript">
var Class = {
//创建类
    create : function () {
        return function () {
            this.initialize.apply(this, arguments);
        };
    }
};

var $A = function (a) {
//转换数组
    return a ? Array.apply(null, a) : new Array;
};

var $ = function (id) {
//获取对象
    return document.getElementById(id);
};

var $break = new Object();

Function.prototype.bind = function () {
//绑定事件
    var wc = this, a = $A(arguments), o = a.shift();
    return function () {
        return wc.apply(o, a.concat($A(arguments)));
    };
};

Object.extend = function (a, b) {
//追加方法
    for (var i in b) a[i] = b[i];
    return a;
};

var CFormat = Class.create();

CFormat.KEY_Tree = Class.create();

CFormat.KEY_Tree.prototype = {
   
    initialize : function (code, end, floor) {
    //初始化成员
        var wc = this;
        wc.items = {};
        wc.code = code || "";
        wc.end = end || null;
        wc.floor = floor || 0;
    },
   
    add : function (code, end, floor) {
    //添加关键字
        var wc = this, items = wc.items;
       
        return !items[code] ? items[code] = new CFormat.KEY_Tree(code, end, floor) : (function () {
            if (end) {
                items[code].end = end;
                items[code].floor = floor;
            }
            return items[code];
        })();
    }
   
};

CFormat.prototype = {
   
    initialize : function () {
    //初始化成员
        var wc = this;
       
        wc.floor = 0; //记录层数
        wc.$C = 0 //进度指针
        wc.$Code = ""; //被摧残内容
       
        wc.$KEY_Tree = new CFormat.KEY_Tree; //关键字排列集合
       
        wc.$DKH = 0; //大括号*暂没用到
        wc.$XKH = 0; //小括号
        wc.$FOR = []; //记录循环数量
       
        wc.$FH = false; //分号*暂没用到
        wc.$_S = false; ///s*暂没用到
        wc.$WH = false; //问好*暂没用到
        wc.$FH = false; //分号*暂没用到
       
        wc.$YSF = /([/?/|/&/:])/; //运算符(双位运算符还没做的说)
       
        wc.$KEY_BOOL = true; //关键字开关
        wc.$KEY_EXT = /[/s/{/}/;/(/)]/; //关键字结尾
       
        wc.$_NBSP = wc.$_BR = wc.$_TAB = ""; //空格/换行/TABLE
        wc.$TSFH = null; //特殊符号
       
        wc.load_js();
        wc.set_type();
    },
   
    $Add_Key : function (code) {
    //把所有关键字放进对象
        var wc = this, $Ary = code.split(","), $Tree, ary, i, j;
       
        for (i = 0 ; i < $Ary.length ; i ++)
            for ($Tree = wc.$KEY_Tree, ary = $Ary[i].split(""), j = 0 ; j < ary.length ; j ++) {
                if (j + 1 == ary.length) $Tree = $Tree.add(ary[j], $Ary[i], j + 1);
                else $Tree = $Tree.add(ary[j]);
            }
    },
   
    load_js : function () {
    //加载关键字
        var wc = this;
        wc.$Add_Key("if,else,for,do,while,switch,case,function,try,catch,var,new,delete,return,in,typeof,throw");
    },
   
    $E : function (func) {
    //处理注释/引号
        var wc = this, temp = {}, args = Array.prototype.slice.call(arguments, 1), code = wc.$Code,
        n_str = code.charAt(wc.$C), $Ary = [wc.$TSFH[n_str] || n_str];
        try {
            while (wc.$C ++ < code.length) {
                n_str = code.charAt(wc.$C), $Ary[$Ary.length] = (wc.$TSFH[n_str] || n_str);
                func.call(temp, n_str, args);
            }
        } catch (exp) {
            if (exp != $break) throw exp;
        }
        return $Ary.join("");
    },
   
    $HL_Line : function () {
    //忽略换行
        var wc = this;
        while (//s/.test(wc.$Code.charAt(wc.$C + 1))) wc.$C ++;
    },
   
    $Y : function (code_n, key) {
    //单引号/双引号
        var wc = this;
        if (!wc.$Z && code_n == "//") wc.$Z = true;
        else {
            if (!wc.$Z && code_n == key[0]) throw $break;
            wc.$Z = false;
        }
    },
   
    $YHZY : function (code_n) {
    //单行注释
        if (code_n == "/n") throw $break;
    },
   
    $DHZY : function (code_n) {
    //多行注释
        var wc = this;
        if (code_n == "*") wc.$B = true;
        else {
            if (wc.$B && code_n == "//") throw $break;
            wc.$B = false;
        }
    },
   
    $REG : function (ary) {
    //检索是否为正则
        var pat_1 = //s$/, pat_2 = /[/w/)/]]/s*$/, i = ary.length - 1;
        while (pat_1.test(ary[i])) {
            if (ary[i].length > 1) return pat_2.test(ary[i]);
            else i --;
        }
        return /[/w/)/]]/.test(ary[i]);
    },
   
    $Re_End_S : function (t_val) {
    //替换结尾换行
        return t_val.replace(//s+$/, "");
    },
   
    $FOR_ING : function () {
    //判断是否在循环括号内
        var wc = this;
        return wc.$FOR.length > 0 && wc.$FOR[wc.$FOR.length - 1] == wc.$XKH - 1;
    },
   
    br : function (bool) {
        var wc = this;
        return (bool ? wc.$_BR : "") + new Array(wc.floor + 1).join(wc.$_TAB);
    },
   
    parse : function (textaret) {
    //格式化
        var wc = this, $K = wc.$KEY_Tree, code = wc.$Code = textaret.value, $ary = [], code_n, regexp_bool;
       
        for (wc.$C = 0 ; wc.$C < code.length ; wc.$C ++) {
            code_n = code.charAt(wc.$C);
           
            if (code_n == " " || code_n == "/t") {
            //处理空格和TABLE
                wc.$KEY_BOOL = true;
                if (code_n == " " && wc.$FOR_ING()) {
                    if ("undefined" != typeof $ary[$ary.length - 1])
                        $ary[$ary.length - 1] = wc.$Re_End_S($ary[$ary.length - 1]);
                    $ary[$ary.length] = wc.$TSFH[code_n];
                    wc.$HL_Line();
                }
            } else if (code_n == "/r" || code_n == "/n") {
            //处理换行缩进
                wc.$KEY_BOOL = true;
                if (wc.floor > 0) {
                    if (code_n == "/r") wc.$C ++;
                    if (/[^/r/n]/.test(code.charAt(wc.$C + 1))) $ary[$ary.length] = wc.br(true);
                } else {
                    $ary[$ary.length] = wc.$TSFH[code_n];
                }
            } else if (code_n == "'" || code_n == "/"") {
            //处理引号
                wc.$KEY_BOOL = true, $ary[$ary.length] = wc.$E(wc.$Y, code_n);
            } else if (code_n == "//") {
            //处理注释
                wc.$KEY_BOOL = true, regexp_bool = false;
                switch (code.charAt(wc.$C + 1)) {
                    case "//" : $ary[$ary.length] = wc.$E(wc.$YHZY); break;
                    case "*" : $ary[$ary.length] = wc.$E(wc.$DHZY); break;
                    default : if (wc.$REG($ary)) {
                        $ary[$ary.length] = code_n;
                    } else {
                        $ary[$ary.length] = wc.$E(wc.$Y, "//");
                    }
                    regexp_bool = true;
                }
                $ary[$ary.length - 1] = wc.$Re_End_S($ary[$ary.length - 1]);
                if (!regexp_bool) $ary[$ary.length] = wc.br(true);
                wc.$HL_Line();
            } else if (code_n == "{") {
            //处理大括号开始
                wc.$KEY_BOOL = true, wc.floor ++;
                if ("undefined" != typeof $ary[$ary.length - 1])
                    $ary[$ary.length - 1] = wc.$Re_End_S($ary[$ary.length - 1])
                $ary[$ary.length] = "{" + wc.br(true);
                wc.$HL_Line();
            } else if (code_n == "}") {
            //处理大括号结束
                wc.$KEY_BOOL = true, wc.floor = Math.max(0,  wc.floor - 1);
                if ("undefined" != typeof $ary[$ary.length - 1])
                    $ary[$ary.length - 1] = wc.$Re_End_S($ary[$ary.length - 1]) + wc.br(true) + "}";
            } else if (code_n == "(") {
            //处理小括号开始
                wc.$KEY_BOOL = true;
                if (wc.$FOR.length > 0) wc.$XKH ++;
                $ary[$ary.length] = "(";
            } else if (code_n == ")") {
            //处理小括号结束
                wc.$KEY_BOOL = true;
                if (wc.$FOR.length > 0) {
                    wc.$XKH --;
                    if (wc.$FOR[wc.$FOR.length - 1] == wc.$XKH) wc.$FOR.pop();
                }
                $ary[$ary.length] = ")";
            } else if (code_n == ";") {
            //处理分号
                wc.$KEY_BOOL = true;
               
                if ("undefined" != typeof $ary[$ary.length - 1])
                    $ary[$ary.length - 1] = wc.$Re_End_S($ary[$ary.length - 1]);
                   
                if (wc.$FOR_ING()) $ary[$ary.length] = wc.$_NBSP + ";" + wc.$_NBSP;
                else $ary[$ary.length] = ";" + wc.br(true);
                wc.$HL_Line();
            } else if (wc.$YSF.test(code_n)) {
            //处理运算符
                wc.$KEY_BOOL = true;
                if ("undefined" != typeof $ary[$ary.length - 1])
                    $ary[$ary.length - 1] = wc.$Re_End_S($ary[$ary.length - 1]);
               
                $ary[$ary.length] = wc.$_NBSP + code_n;
                while (wc.$YSF.test(code.charAt(wc.$C + 1))) {
                    wc.$C ++, $ary[$ary.length] = RegExp.$1;
                }
                $ary[$ary.length] = wc.$_NBSP;
                wc.$HL_Line();
            } else if (code_n == ",") {
            //处理逗号
                wc.$KEY_BOOL = true, $ary[$ary.length] = "," + wc.$_NBSP;
            } else if (code_n == "<" || code_n == ">") {
            //暂时先把它们转义以后在处理双为运算符
                wc.$KEY_BOOL = true, $ary[$ary.length] = wc.$TSFH[code_n];
            } else if (code_n == "=") {
            //等号先仍这。。
                wc.$KEY_BOOL = true, $ary[$ary.length] = code_n;
            } else {
            //暂无规定
                if (wc.$KEY_BOOL && $K.items[code_n]) {
                //匹配是否为关键字
                    $ary[$ary.length] = code_n;
                    $K = $K.items[code_n];
                    if ($K.end && wc.$KEY_EXT.test(code.charAt(wc.$C + 1))) {
                    //匹配是否完整
                        if ($K.end == "for") wc.$FOR[wc.$FOR.length] = wc.$XKH;
                        $K = wc.$KEY_Tree, $ary[$ary.length] = wc.$_NBSP;
                        wc.$HL_Line();
                    } else if (!$K.items[code.charAt(wc.$C + 1)]) {
                    //如不完整则清空存储
                        $K = wc.$KEY_Tree, wc.$KEY_BOOL = false;
                    }
                } else {
                    $ary[$ary.length] = code_n;
                }
               
            }
        }
        return $ary.join("");
    },
   
    set_type : function (type) {
        var wc = this, ep;
        if (type == "html") {
        //图网把这部分代码给替换了,寒,那改成和下面一样的好了。。。反正这个HTML部分也没什么大用^^
            wc.$_BR = "/n", wc.$_TAB = "/t", wc.$_NBSP = " ";
            ep = { "/"" : "/"", "'" : "'", ">" : ">", "<" : "<" };
        } else {
            wc.$_BR = "/n", wc.$_TAB = "/t", wc.$_NBSP = " ";
            ep = { "/"" : "/"", "'" : "'", ">" : ">", "<" : "<" };
        }
        wc.$TSFH = { " " : wc.$_NBSP, "/r" : "", "/n" : wc.$_BR, "/t" : wc.$_TAB }; //设置字符
        Object.extend(wc.$TSFH, ep);
    }
   
};

var f = new CFormat;
f.load_js();

var bh_dis = function (a, b) {
    a.style.display = b;
};

var parse = function () {
    var wc = $("code"), status = $("status"), type = $("type").value, time;
   
    f.set_type(type);
   
    time = new Date;
    if (type == "html") {
        status.innerHTML = f.parse(wc);
        bh_dis(wc, "none");
        bh_dis(status, "block");
    } else {
        wc.value = f.parse(wc);
        bh_dis(wc, "block");
        bh_dis(status, "none");
    }
    alert(new Date() - time + "ms");
};

var reset = function () {
    bh_dis($("code"), "block");
    bh_dis($("status"), "none");
};
</script>
</head>
<body>
<input type="button" onclick="parse()" value="format" />
<select id="type">
<option value="code">CODE格式</option>
<option value="html">HTML格式</option>
</select>
<input type="button" onclick="reset()" value="reset" />
<hr />
<div id="status" style="display:none;"> </div>
<textarea id="code">
if (/Konqueror|Safari|KHTML/.test(navigator.userAgent))

get_cookie : function (){//获取COOKIE;
return (/CDrag=([^;]+)(?:;|$)/.exec(document.cookie) || [, ])[1];}
!function () {for (i = 0 ; i < -function () {return -10}() ; i ++) { alert(i); }
    alert(i);
}
</textarea>
</body>
</html>

原创粉丝点击