Created
November 8, 2017 18:13
-
-
Save mopperwhite/a72e687e1663d8c50826652422a7f98b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function parse_switchy(text){ | |
return text | |
.split("\n") | |
.filter(l => l.length && l[0] == '*') | |
.map(l => l.split(' ')) | |
} | |
function switchy2tire_if(text){ | |
function tree2if(tree){ | |
function t2i(node, depth, defa){ | |
if(typeof node === 'number') return node.toString(); | |
defa = node['.'] || defa | |
let keys = Object.keys(node).filter(s => s!='.') | |
let sms = keys.map(k => `t[${depth}]=='${k}'?${t2i(node[k], depth+1, defa)}`) | |
if(sms.length){ | |
sms.push(defa.toString()) | |
return '('+sms.join(':')+')' | |
}else{ | |
return defa.toString() | |
} | |
} | |
return `function(t){return ${t2i(tree, 0, tree['.'])}}` | |
} | |
const records = parse_switchy(text) | |
const tree = {['.']: 'DIRECT'} | |
let proxy_id_counter = 0 | |
const proxy_id_map = {} | |
const proxy_vec = [] | |
for(let [pat, pro] of records){ | |
const host = pat.split('.').reverse() | |
let head = tree | |
let part = host.shift() | |
while(host.length && part != '*'){ | |
head = head[part] ? head[part] : (head[part] = {}) | |
part = host.shift() | |
} | |
if(proxy_id_map[pro]){ | |
head['.'] = proxy_id_map[pro] | |
}else{ | |
proxy_id_map[pro] = proxy_id_counter | |
head['.'] = proxy_id_counter | |
proxy_vec.push(pro) | |
proxy_id_counter ++ | |
} | |
} | |
return ` | |
function FindProxyForURL(url, host){ | |
let t = FindProxyForURL.func(host.split('.').reverse()) | |
return FindProxyForURL.vec[t] | |
} | |
FindProxyForURL.func = ${tree2if(tree)}; | |
FindProxyForURL.vec = ${JSON.stringify(proxy_vec)}; | |
` | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment