2018-11-09 18:57:24 +00:00
|
|
|
'use strict'
|
|
|
|
const indent = require('indent-string')
|
|
|
|
const config = require('./config')
|
|
|
|
|
2018-12-01 17:29:44 +00:00
|
|
|
function print(input, options = {}) {
|
|
|
|
const {expanded} = options
|
2018-11-09 18:57:24 +00:00
|
|
|
const index = new Map()
|
|
|
|
let row = 0
|
|
|
|
|
|
|
|
function doPrint(v, path = '') {
|
|
|
|
index.set(row, path)
|
|
|
|
|
|
|
|
const eol = () => {
|
|
|
|
row++
|
|
|
|
return '\n'
|
|
|
|
}
|
|
|
|
|
|
|
|
if (typeof v === 'undefined') {
|
|
|
|
return void 0
|
|
|
|
}
|
|
|
|
|
|
|
|
if (v === null) {
|
|
|
|
return config.null(v)
|
|
|
|
}
|
|
|
|
|
|
|
|
if (typeof v === 'number' && Number.isFinite(v)) {
|
|
|
|
return config.number(v)
|
|
|
|
}
|
|
|
|
|
|
|
|
if (typeof v === 'boolean') {
|
|
|
|
return config.boolean(v)
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
if (typeof v === 'string') {
|
|
|
|
return config.string(JSON.stringify(v))
|
|
|
|
}
|
|
|
|
|
|
|
|
if (Array.isArray(v)) {
|
2018-12-07 15:51:10 +00:00
|
|
|
let output = config.bracket('[')
|
2018-11-09 18:57:24 +00:00
|
|
|
const len = v.length
|
|
|
|
|
2018-12-07 15:51:10 +00:00
|
|
|
if (len > 0) {
|
|
|
|
if (expanded && !expanded.has(path)) {
|
|
|
|
output += '\u2026'
|
|
|
|
} else {
|
|
|
|
output += eol()
|
|
|
|
let i = 0
|
|
|
|
for (let item of v) {
|
|
|
|
const value = typeof item === 'undefined' ? null : item // JSON.stringify compatibility
|
|
|
|
output += indent(doPrint(value, path + '[' + i + ']'), config.space)
|
|
|
|
output += i++ < len - 1 ? config.comma(',') : ''
|
|
|
|
output += eol()
|
|
|
|
}
|
|
|
|
}
|
2018-11-09 18:57:24 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return output + config.bracket(']')
|
|
|
|
}
|
|
|
|
|
|
|
|
if (typeof v === 'object' && v.constructor === Object) {
|
2018-12-07 15:51:10 +00:00
|
|
|
let output = config.bracket('{')
|
2018-11-09 18:57:24 +00:00
|
|
|
|
2018-12-07 15:51:10 +00:00
|
|
|
const entries = Object.entries(v).filter(([key, value]) => typeof value !== 'undefined') // JSON.stringify compatibility
|
2018-11-09 18:57:24 +00:00
|
|
|
const len = entries.length
|
|
|
|
|
2018-12-07 15:51:10 +00:00
|
|
|
if (len > 0) {
|
|
|
|
if (expanded && !expanded.has(path)) {
|
|
|
|
output += '\u2026'
|
|
|
|
} else {
|
|
|
|
output += eol()
|
|
|
|
let i = 0
|
|
|
|
for (let [key, value] of entries) {
|
|
|
|
const part = config.key(JSON.stringify(key)) + config.colon(':') + ' ' + doPrint(value, path + '.' + key)
|
|
|
|
output += indent(part, config.space)
|
|
|
|
output += i++ < len - 1 ? config.comma(',') : ''
|
|
|
|
output += eol()
|
|
|
|
}
|
|
|
|
}
|
2018-11-09 18:57:24 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return output + config.bracket('}')
|
|
|
|
}
|
|
|
|
|
2018-12-07 15:51:10 +00:00
|
|
|
return JSON.stringify(v, null, config.space)
|
2018-11-09 18:57:24 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return [doPrint(input), index]
|
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = print
|