index.js
1.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
var util = require('util')
var INDENT_START = /[\{\[]/
var INDENT_END = /[\}\]]/
module.exports = function() {
var lines = []
var indent = 0
var push = function(str) {
var spaces = ''
while (spaces.length < indent*2) spaces += ' '
lines.push(spaces+str)
}
var line = function(fmt) {
if (!fmt) return line
if (INDENT_END.test(fmt.trim()[0]) && INDENT_START.test(fmt[fmt.length-1])) {
indent--
push(util.format.apply(util, arguments))
indent++
return line
}
if (INDENT_START.test(fmt[fmt.length-1])) {
push(util.format.apply(util, arguments))
indent++
return line
}
if (INDENT_END.test(fmt.trim()[0])) {
indent--
push(util.format.apply(util, arguments))
return line
}
push(util.format.apply(util, arguments))
return line
}
line.toString = function() {
return lines.join('\n')
}
line.toFunction = function(scope) {
var src = 'return ('+line.toString()+')'
var keys = Object.keys(scope || {}).map(function(key) {
return key
})
var vals = keys.map(function(key) {
return scope[key]
})
return Function.apply(null, keys.concat(src)).apply(null, vals)
}
if (arguments.length) line.apply(null, arguments)
return line
}