-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathas-literal.js
65 lines (59 loc) · 1.59 KB
/
as-literal.js
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
62
63
64
65
'use strict'
module.exports = asLiteral
var asObjectKey = require('./as-object-key.js')
function asLiteral (thing) {
if (thing === null) return 'null'
if (thing == null) return 'undefined'
if (typeof thing === 'boolean' || typeof thing === 'number') {
return thing.toString()
} else if (typeof thing === 'string') {
return asStringLiteral(thing)
} else if (thing instanceof Array) {
return asArrayLiteral(thing)
} else {
return asObjectLiteral(thing)
}
}
function asStringLiteral (thing) {
var str = thing.toString()
.replace(/\\/g, '\\\\')
.replace(/[\0]/g, '\\0')
.replace(/[\b]/g, '\\b')
.replace(/[\f]/g, '\\f')
.replace(/[\n]/g, '\\n')
.replace(/[\r]/g, '\\r')
.replace(/[\t]/g, '\\t')
.replace(/[\v]/g, '\\v')
if (/'/.test(str) && !/"/.test(str)) {
return '"' + str + '"'
} else {
return "'" + str.replace(/'/g, "\\'") + "'"
}
}
function asArrayLiteral (thing) {
if (!thing.length) return '[ ]'
var arr = '[\n'
function arrayItem (item) {
return asLiteral(item).replace(/\n(.*)(?=\n)/g, '\n $1')
}
arr += arrayItem(thing.shift())
thing.forEach(function (item) {
arr += ',\n' + arrayItem(item)
})
arr += '\n]'
return arr
}
function asObjectLiteral (thing) {
var keys = Object.keys(thing)
if (!keys.length) return '{ }'
var obj = '{\n'
function objectValue (key) {
return asObjectKey(key) + ': ' + asLiteral(thing[key]).replace(/\n(.*)(?=\n)/g, '\n $1')
}
obj += objectValue(keys.shift())
keys.forEach(function (key) {
obj += ',\n' + objectValue(key)
})
obj += '\n}'
return obj
}