on e9834ee help sign in
webring/scripts/indental.js
59 lines 1.6 kB history raw
1'use strict'
3function indental (data, Type) {
4 function formatLine (line) {
5 const a = []
6 const h = {}
7 for (const id in line.children) {
8 const child = line.children[id]
9 if (child.key) {
10 if (h[child.key]) { console.warn(`Redefined key: ${child.key}.`) }
11 h[child.key] = child.value
12 } else if (child.children.length === 0 && child.content) {
13 a[a.length] = child.content
14 } else {
15 h[child.content.toUpperCase()] = formatLine(child)
16 }
17 }
18 return a.length > 0 ? a : h
19 }
21 function makeLine (line) {
22 return line.indexOf(' : ') > -1 ? {
23 indent: line.search(/\S|$/),
24 content: line.trim(),
25 key: line.split(' : ')[0].trim().toUpperCase(),
26 value: line.split(' : ')[1].trim()
27 } : {
28 indent: line.search(/\S|$/),
29 content: line.trim(),
30 children: []
31 }
32 }
34 function skipLine (line) {
35 return line.trim() !== '' && line.substr(0, 1) !== ';'
36 }
38 const lines = data.split('\n').filter(skipLine).map(makeLine)
40 // Assoc
41 const stack = {}
42 for (const id in lines) {
43 const line = lines[id]
44 const target = stack[line.indent - 2]
45 if (target) { target.children.push(line) }
46 stack[line.indent] = line
47 }
49 // Format
50 const h = {}
51 for (const id in lines) {
52 const line = lines[id]
53 if (line.indent > 0) { continue }
54 const key = line.content.toUpperCase()
55 if (h[key]) { console.warn(`Redefined key: ${key}, line ${id}.`) }
56 h[key] = Type ? new Type(key, formatLine(line)) : formatLine(line)
57 }
58 return h