indental.js (1409B)
1 function Indental(data) 2 { 3 this.data = data; 4 5 this.parse = function(type) 6 { 7 var lines = this.data.split("\n").map(liner) 8 9 // Assoc lines 10 var stack = {} 11 var target = lines[0] 12 for(id in lines){ 13 var line = lines[id] 14 if(line.skip){ continue; } 15 target = stack[line.indent-1]; 16 if(target){ target.children[target.children.length] = line } 17 stack[line.indent] = line 18 } 19 20 // Format 21 var h = {} 22 for(id in lines){ 23 var line = lines[id]; 24 if(line.skip || line.indent > 0){ continue; } 25 var key = _.snakeCase(line.content) 26 h[key] = type ? new type(key,format(line)) : format(line) 27 } 28 return h 29 } 30 31 function format(line) 32 { 33 var a = []; 34 var h = {}; 35 for(id in line.children){ 36 var child = line.children[id]; 37 if(child.key){ h[_.snakeCase(child.key)] = child.value } 38 else if(child.children.length == 0 && child.content){ a[a.length] = child.content } 39 else{ h[_.snakeCase(child.content)] = format(child) } 40 } 41 return a.length > 0 ? a : h 42 } 43 44 function liner(line) 45 { 46 return { 47 indent:line.search(/\S|$/), 48 content:line.trim(), 49 skip:line == "" || line.substr(0,1) == "~", 50 key:line.indexOf(" : ") > -1 ? _.snakeCase(line.split(" : ")[0].trim()) : null, 51 value:line.indexOf(" : ") > -1 ? line.split(" : ")[1].trim() : null, 52 children:[] 53 } 54 } 55 }