UNPKG

@wuapi/generator

Version:
126 lines (125 loc) 3.33 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.flatBra = exports.bra = exports.BraceCaller = exports.Brace = exports.indent = void 0; /** * Add indent to all lines of input string. * Empty lines are skipped. * @param s The string about to indent * @returns Intented string */ function indent(s) { //const indentSpaces = 4 //const spaces = Array(indentSpaces).join(" ") const spaces = " "; return s.replace(/^(?!$)/mg, spaces); } exports.indent = indent; /** * A class to help create create blocks encapsulated with braces * +-----------------------------------+ * | [prefix] { | Brace * | [line] | * | ... | * | +------------+ | * | | [prefix] { | Child Brace | * | | } | | * | +------------+ | * | [line] | * | } | * +-----------------------------------+ */ class Brace { /** * * @param prefix THe prefix to brance */ constructor(prefix) { this.prefix = prefix; /** * * brace: | nobrace: | pbrace: * -------------+--------------+-------------- * | | * [prefix] { | [prefix] | [prefix] * [line] | [line] | [line] * [line] | [line] | [line] * ... | ... | ... * } | | * | | */ this.type = "brace"; /** * The content */ this.list = []; } /** * * @param item */ add(item) { if (item instanceof Function) { const proxy = new Proxy(new BraceCaller(this), { apply: (target, thisArg, parameters) => { target._call(parameters[0]); } }); item(proxy); } else { this.list.push(item); } return this; } toString() { let result = ""; for (let s of this.list) { if (s instanceof Brace) { result += s.toString() + "\n"; } else { result += s + "\n"; } } if (this.type != "flat") { result = indent(result); } return this.type == "brace" ? `${this.prefix}{\n${result}}\n` : `${this.prefix}\n${result}`; } } exports.Brace = Brace; /** * The argument for */ class BraceCaller extends Function { constructor(brace) { super(); this.brace = brace; } _call(item) { this.brace.add(item); } bra(prefix) { const child = new Brace(prefix); this.brace.add(child); return child; } } exports.BraceCaller = BraceCaller; /** * Convenient function to create Brace instance. * @param prefix * @returns Newly created Brace instance */ function bra(prefix) { return new Brace(prefix); } exports.bra = bra; function flatBra(prefix) { const brace = new Brace(prefix); brace.type = "flat"; return brace; } exports.flatBra = flatBra;