Skip to content

Commit

Permalink
处理重复变量
Browse files Browse the repository at this point in the history
  • Loading branch information
sunxinyu committed Mar 4, 2016
1 parent eddf682 commit 9970dc8
Show file tree
Hide file tree
Showing 5 changed files with 29 additions and 10 deletions.
2 changes: 1 addition & 1 deletion README.md
Expand Up @@ -22,7 +22,7 @@ todolist

* 翻译属性名
* 多个文件联合编译


示例:

Expand Down
4 changes: 2 additions & 2 deletions bin/cli
Expand Up @@ -4,9 +4,9 @@
var HanCode = require('../index.js')
var path = require("path");
var argv = require('minimist')(process.argv.slice(2));
var source = argv.s;
var source = path.join(process.cwd(),argv.s);
var fs = require("fs");
HanCode(fs.readFileSync(path.join(process.cwd(),source),'utf-8'),function(err,code){
HanCode(fs.readFileSync(source,'utf-8'),function(err,code){
var result_path = source.replace(".js",".汉.js");
console.log("编译成功,目标路径:"+result_path)
fs.writeFileSync(result_path,code,'utf-8')
Expand Down
26 changes: 23 additions & 3 deletions index.js
Expand Up @@ -37,26 +37,46 @@ module.exports = function(source_code,callback){


for_trans_words = _.uniq(for_trans_words);
console.log(for_trans_words)
//console.log(for_trans_words)
/*--------找出所有需要翻译的单词---------*/
console.log("翻译中");
translate_util(for_trans_words,function(e,result){
translate_obj = result;
makeUniqObject(translate_obj);
/*--------替换所有单词-----------------*/
varNodes.forEach(function(node){
node.name = translate_obj[node.name]||node.name;
})
refNodes.forEach(function(node){
node.name = translate_obj[node.name]||node.name;
})
//console.log("编译前:")
//console.log(source_code)
callback(null,ast_code.print_to_string({
beautify:true
}));

})
}

/**
* 把一个object里的value都变成唯一的,如果不是唯一的,给他加_1
* @param obj
*/
var makeUniqObject = function(obj){
var scaned_values = []
for(var i in obj){
var value = obj[i];
if(scaned_values.indexOf(value)!=-1){

var repeat_count = 0;
scaned_values.forEach(function(v){
if(v==value){
repeat_count++;
}
})
obj[i] = value+"_"+repeat_count
}
scaned_values.push(value);
}
}


2 changes: 1 addition & 1 deletion package.json
@@ -1,6 +1,6 @@
{
"name": "hancode",
"version": "1.0.7",
"version": "1.1.2",
"description": "把js代码里的变量翻译成中文",
"main": "index.js",
"scripts": {
Expand Down
5 changes: 2 additions & 3 deletions translate_util.js
Expand Up @@ -64,7 +64,6 @@ module.exports = function(strs,callback){
to: to,
sign: sign
}
console.log(qs)
request.get({
url: 'http://api.fanyi.baidu.com/api/trans/vip/translate',
qs: {
Expand All @@ -76,13 +75,13 @@ module.exports = function(strs,callback){
sign: sign
}
},function(e,r,body){
console.log(body)
var result = {},res;
try{
res = JSON.parse(body);
if(res.trans_result){
res.trans_result.forEach(function(r){
result[wordTransformTemp[r.src]||r.src] = r.dst.replace(/ /g,"_").replace(/ /g,"");
var dst = r.dst.replace(/ /g,"_");
result[wordTransformTemp[r.src]||r.src] = dst;
})
}
}catch(e){
Expand Down

0 comments on commit 9970dc8

Please sign in to comment.