@carlosv2/glue
Version:
Dependency injection library that stays out of the way
35 lines (34 loc) • 1.45 kB
JavaScript
import ts from 'typescript';
import { isArray, isBoolean, isDictionary, isNumber, isString, isUndefined, } from './utils.js';
import { DiError } from './error.js';
const { factory, SyntaxKind } = ts;
export class Compilable {
compileArg(importer, value) {
if (isString(value)) {
return factory.createStringLiteral(value);
}
if (isNumber(value)) {
let compiled = factory.createNumericLiteral(Math.abs(value));
if (value < 0) {
compiled = factory.createPrefixUnaryExpression(SyntaxKind.MinusToken, compiled);
}
return compiled;
}
if (isBoolean(value)) {
return value ? factory.createTrue() : factory.createFalse();
}
if (isUndefined(value)) {
return factory.createIdentifier('undefined');
}
if (isArray(value)) {
return factory.createArrayLiteralExpression(value.map(item => this.compileArg(importer, item)));
}
if (value instanceof Compilable) {
return value.compile(importer);
}
if (isDictionary(value)) {
return factory.createObjectLiteralExpression(Object.entries(value).map(([key, item]) => factory.createPropertyAssignment(factory.createIdentifier(key), this.compileArg(importer, item))));
}
throw new DiError(`Requested to compile unknown data type \`${JSON.stringify(value)}\``);
}
}