@jsonjoy.com/json-type
Version:
High-performance JSON Pointer implementation
60 lines (59 loc) • 1.9 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.ObjValue = void 0;
const Value_1 = require("./Value");
const TypeSystem_1 = require("../system/TypeSystem");
const printTree_1 = require("tree-dump/lib/printTree");
class ObjValue extends Value_1.Value {
get system() {
return this.type.getSystem();
}
get t() {
return this.system.t;
}
keys() {
const type = this.type;
return type.fields.map((field) => field.key);
}
get(key) {
const field = this.type.getField(key);
if (!field)
throw new Error('NO_FIELD');
const type = field.value;
const data = this.data[key];
return new Value_1.Value(type, data);
}
field(field, data) {
field = typeof field === 'function' ? field(this.type.getSystem().t) : field;
this.data[field.key] = data;
const type = this.type;
const system = type.system;
if (!system)
throw new Error('NO_SYSTEM');
type.fields.push(field);
return this;
}
add(key, type, data) {
const system = this.type.getSystem();
const t = system.t;
type = typeof type === 'function' ? type(t) : type;
return this.field(t.prop(key, type), data);
}
set(key, value) {
return this.add(key, value.type, value.data);
}
merge(obj) {
Object.assign(this.data, obj.data);
const type = this.type;
const system = type.system;
if (!system)
throw new Error('NO_SYSTEM');
type.fields.push(...type.fields);
return this;
}
toString(tab = '') {
return 'ObjValue' + (0, printTree_1.printTree)(tab, [(tab) => this.type.toString(tab)]);
}
}
exports.ObjValue = ObjValue;
ObjValue.new = (system = new TypeSystem_1.TypeSystem()) => new ObjValue(system.t.obj, {});