Co-authored-by: Andrew Eisenberg <aeisenberg@github.com> Co-authored-by: Henry Mercer <henrymercer@github.com>
63 lines
1.9 KiB
JavaScript
63 lines
1.9 KiB
JavaScript
"use strict";
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.Literal = void 0;
|
|
const Node_1 = require("./Node");
|
|
const ConditionalOutput_1 = require("./ConditionalOutput");
|
|
const is_plain_object_1 = require("./is-plain-object");
|
|
/**
|
|
* A literal source representation of the provided object
|
|
*/
|
|
class Literal extends Node_1.Node {
|
|
constructor(object) {
|
|
super();
|
|
this.tokens = flatten(object);
|
|
}
|
|
get childNodes() {
|
|
return this.tokens;
|
|
}
|
|
toCodeString() {
|
|
return this.tokens
|
|
.map((node) => {
|
|
if (typeof node === 'string')
|
|
return node;
|
|
if (node instanceof Node_1.Node)
|
|
return node.toCodeString();
|
|
return '';
|
|
})
|
|
.join(' ');
|
|
}
|
|
}
|
|
exports.Literal = Literal;
|
|
function flatten(o) {
|
|
if (typeof o === 'undefined') {
|
|
return ['undefined'];
|
|
}
|
|
if (typeof o === 'object' && o != null) {
|
|
if (o instanceof Node_1.Node || o instanceof ConditionalOutput_1.MaybeOutput) {
|
|
return [o];
|
|
}
|
|
else if (Array.isArray(o)) {
|
|
const nodes = ['['];
|
|
for (let i = 0; i < o.length; i++) {
|
|
if (i !== 0)
|
|
nodes.push(',');
|
|
nodes.push(...flatten(o[i]));
|
|
}
|
|
nodes.push(']');
|
|
return nodes;
|
|
}
|
|
else if (is_plain_object_1.isPlainObject(o)) {
|
|
const nodes = ['{'];
|
|
const entries = Object.entries(o);
|
|
for (let i = 0; i < entries.length; i++) {
|
|
if (i !== 0)
|
|
nodes.push(',');
|
|
const [key, value] = entries[i];
|
|
nodes.push(JSON.stringify(key), ':', ...flatten(value));
|
|
}
|
|
nodes.push('}');
|
|
return nodes;
|
|
}
|
|
}
|
|
return [JSON.stringify(o)];
|
|
}
|